按下按钮验证以及输入密钥

时间:2013-06-28 12:08:01

标签: jquery

我是jquery的新手,所以我在这里阅读了一些关于如何通过单击按钮来验证表单以及按Enter并跟随它们的stackoverflow示例。出于某种原因,我的代码没有你可以解释一下我的错误吗?提前谢谢!

$(document).keyup(function(event) {
    if(event.keyCode == 13){
    $("#clickButton").click(function () {
        var username = document.forms["form1"]["username"];
        var password = document.forms["form1"]["password"];
        var numbers = /^[0-9]+$/;
        if (username.value == "" || password.value == "") {
            alert("Data missing");
        } else if (username.value.match(numbers)) {
            alert('Data not valid');
        } else {
            alert("Your password is " + password.value);
        }
    });
}
});

3 个答案:

答案 0 :(得分:1)

应该是

<强> DEMO

$("#clickButton").click(function () {
    var username = document.forms["form1"]["username"];
    var password = document.forms["form1"]["password"];
    var numbers = /^[0-9]+$/;
    if (username.value == "" || password.value == "") {
        alert("Data missing");
    } else if (username.value.match(numbers)) {
        alert('Data not valid');
    } else {
        alert("Your password is " + password.value);
    }
});

$('input').keyup(function(event) {
if(event.keyCode == 13){
    $("#clickButton").click();
}
});

答案 1 :(得分:1)

您在键盘内绑定了一个点击,因此每次按下回车键时,都会绑定一个新的点击处理程序,这是禁止的。

$('#formId input').on('keyup', function(event) {
    if(event.which === 13) {
        event.preventDefault();
        validate();
    }
});

$("#clickButton").on('click', function(event) {
    event.preventDefault();
    validate();
});

function validate() {
    var username = $("#username"), // give elements ID's
        password = $("#password");

    if (username.val() == "" || password.val() == "") {
        alert("Data missing");
    } else if (username.val().match(/^[0-9]+$/)) {
        alert('Data not valid');
    } else {
        alert("Your password is " + password.val());
        document.getElementById('formId').submit();
    }
}

更简单的灵魂就是将验证绑定到表单提交事件,因为在单击提交时以及在输入中按下输入时都会触发:

$('#formId').on('submit', function(e) {
    e.preventDefault();
    var username = $("#username"), // give elements ID's
        password = $("#password");

    if (username.val() == "" || password.val() == "") {
        alert("Data missing");
    } else if (username.val().match(/^[0-9]+$/)) {
        alert('Data not valid');
    } else {
        alert("Your password is " + password.val());
        this.submit();
    }
});

答案 2 :(得分:0)

只需删除点击功能

即可
$(document).keyup(function(event) {
    if(event.keyCode == 13){      
        var username = document.forms["form1"]["username"];
        var password = document.forms["form1"]["password"];
        var numbers = /^[0-9]+$/;
        if (username.value == "" || password.value == "") {
            alert("Data missing");
        } else if (username.value.match(numbers)) {
            alert('Data not valid');
        } else {
            alert("Your password is " + password.value);
        }

}
});