2012-02-24 49 views
1

我已將一個按鍵事件附加到我的文本框中。當用戶按下其他鍵時,我正在做一些處理工作,但是當用戶按下Enter鍵時,我正在將文本框中的值提交給某個服務器。我能夠做所有的處理,每件事情都很好,但是當我按下Enter鍵時,事件並沒有被解僱。所以,我可能無法將我的價值提交給服務器。當我按下回車鍵時,按鍵事件不會被解僱

這裏是我的代碼:

$("#txt" + filterID).keypress(txtInput_keypress); 

function txtInput_keypress(e) { 
    var code = (e.keyCode ? e.keyCode : e.which); 
    var strValue = $(this).val()+ String.fromCharCode(e.which); 
    var bool = $.trim(strValue).match(reg); 
    if (code == 13) { 
     //textbox value submission code 
    } 
    else if (parseFloat($.trim(strValue)) > max) { 
     e.preventDefault(); 
    } 
    else if (bool) { 
     return true; 
    } 
    else { 
     e.preventDefault(); 
    } 
} 

什麼錯我的代碼?請有人幫我解決這個問題。

+0

你沒有傳遞事件或(e)在你的函數中! – adeneo 2012-02-24 05:26:20

+0

@adeneo - jQuery在調用函數時會這樣做。 – nnnnnn 2012-02-24 05:31:51

+0

@nnnnnn - 你是對的,沒有想過,試過這個,但似乎變量reg沒有定義,也許這就是問題,似乎沒有'var bool = ...'行就可以工作。 – adeneo 2012-02-24 05:40:31

回答

1
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
    <title></title> 
    <script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script> 
    <script type="text/javascript"> 
     $(document).ready(function() { 
      var filterID = 1, reg = '^([0-9]|[1-9][0-9]|[1-9][0-9][0-9])$', max = 1000; 

      $("#txt" + filterID).keypress(txtInput_keypress); 

      function txtInput_keypress(e) { 
       var code = (e.keyCode ? e.keyCode : e.which); 
       var strValue = $(this).val() + String.fromCharCode(e.which); 
       var bool = $.trim(strValue).match(reg); 
       if (code == 13) { 
        //textbox value submission code 
        //$('form#test').submit(); // if alert is not coming uncoment this line. 
       } 
       else if (parseFloat($.trim(strValue)) > max) { 
        e.preventDefault(); 
       } 
       else if (bool) { 
        return true; 
       } 
       else { 
        e.preventDefault(); 
       } 
      } 
     });     
    </script> 
</head> 
<body> 
    <form id="test" action="javascript:alert('success!');"> 
    <input type="text" id="txt1" /> 
    </form> 
</body> 
</html> 
+0

filterId,reg,max變量丟失 – Thulasiram 2012-04-19 09:06:05

+0

看到現場演示看到這個鏈接http://jsfiddle.net/nanoquantumtech/ wDKks / – Thulasiram 2012-04-19 09:09:45