当按下回车键时,按键事件不会被触发

时间:2012-02-24 05:11:09

标签: jquery textbox keypress 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();
    }  
} 

我的代码有什么问题?请有人帮我解决这个问题。

1 个答案:

答案 0 :(得分: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>