2012-02-24 51 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