且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在输入按键和两个提交按钮时区分表单提交

更新时间:2022-12-11 13:35:42

您可以执行以下操作(请参阅实时示例):

You could do the following (See Live Example):

$(document).ready(function(){
    $("input[type='text'],input[type='password']").keypress(function(e){
        e.preventDefault();
        if (e.which == 13){
            alert("User pressed 'Enter' in a text input.");
            // do your custom processing here
        }
    });

    $("input[type='submit']").click(function(e){
        e.preventDefault();
        var submitClicked = e.target.id;
        alert("The submit button with id '"+submitClicked+"' was clicked!");

        //probably a switch statement here to do your custom processing based on which submit button was pressed.
    });
});

上面的代码将陷阱在任何文本或密码输入上输入Enter键...将忽略<textarea>上的Enter键输入(我认为这是理想的效果).在任何文本或密码输入上按Enter键都不会触发第一次提交按钮的点击.

The code above will trap for enter keypress on any text or password input... will ignore enter key presses on <textarea> (a desired effect I would think). Pressing enter on any text or password input will NOT trigger the first submit button click.

请注意,您必须使用$([your form selector]).submit();