如何使用jquery按类名验证所有输入不想使用任何插件,如validate

时间:2011-07-27 16:04:07

标签: jquery

我想使用类名来验证所有输入我正在使用以下代码

$('#submitbutton').click(function() {

           $('input.inputme[type=hidden]').each(function () {

                 if($(this).val()==''){
                     choclates='false';
                 }else{
                      choclates='true';
                     }                      
            });
         if(choclates=='true'){
                  $('#choclateform').submit();
                 }else{
                 alert("Please Fill all Boxes.");
                 }

        });

当我发布这个问题代码是不同的并且没有充分工作但这可行但我认为我让它变得复杂可以有人让它变得更好吗?

3 个答案:

答案 0 :(得分:1)

如果您的目标是阻止提交表单,我会在表单上挂钩submit事件,并在空白时从那个处理程序返回false找到字段(以防止提交表单)。

// Hook the submit event
$('#theForm').submit(function() {
    // Assume all will be fine
    var valid = true;

    // Check your inputs
    $('input.inputme[type=text]').each(function () {

        // Is this input's value (effectively) blank? Note that
        // there's no reason whatsoever to use $(this).val(),
        // with text fields this.value gives you the same thing
        // more efficiently.
        // I'm also trimming off whitespace and using the fact
        // that empty strings are "falsey".
        if (!$.trim(this.value)) {
            // Bug user
            alert("Please fill all boxes");

            // Flag that there was a problem
            valid = false;

            // Optionally, stop the `each` loop. If
            // you're *literally* going to use `alert`,
            // then I'd stop the loop or you'll irritate
            // people. But if you're showing some kind
            // of indicator next to the field instead,
            // then I'd leave this off and continue to do
            // all fields.
            return false;
        }
    });

    if (!valid) {
        // Cancel submission
        return false;
    }
});

答案 1 :(得分:0)

这可能会被白色空间抛出!不是吗?检查一下:

$('#submitbutton').click(function() {
    var flag = true;
    $('input.inputme[type=text]').each(function () {
        if(jQuery.trim($(this).val()) == ''){
            alert("Please fill all boxes");
            flag = false;
        }
    });
    return flag;
});

答案 2 :(得分:-1)

试试这个

$('#formId').submit(function() {

   $('input.inputme[type=text]').each(function (e) {

        if($(this).val()=='') {
            alert("Please fill all boxes");

            return false;
        }
    });

});