Jquery中的表单验证为整个表单设置背景颜色,而不是表单元素

时间:2013-08-30 12:15:33

标签: jquery html forms validation

我有一个表单,提交时需要使用jQuery进行验证。通常我会使用jQuery validate插件但遗憾的是在这种情况下不能使用它,因为不需要错误消息,只是样式更改。

请考虑以下代码:

 $(document).ready(function (){
    $('.submitJobform').on('submit', function(e) {
        if( !$('.required').value ){
            $(this).css('background-color','red');
        }

        e.preventDefault();  //prevent form from submitting
    });
 });

按下提交按钮时,如果.required类的文本字段没有值,则整个表单背景变为红色。我认为使用$ this关键字会选择当前没有找到值的值,但事实并非如此。有没有办法强迫$(this)引用有问题的文本项,或者是否有另一种方法,以便只有文本字段的背景变为红色?

提前致谢

Jezzipin

5 个答案:

答案 0 :(得分:3)

$('.submitJobform').on('submit', function (e) {
    $('.required').each(function () {
        if (!this.value) {
            $(this).css('background-color', 'red');
        }
    });
    e.preventDefault(); //prevent form from submitting
});
});

答案 1 :(得分:0)

尝试这一点,但请记住,只有当您的表单只有一个必需元素时,它才会起作用。 如果您有多个必需元素具有“必需”类,那么您必须为选择器运行 foreeach 并相应地处理每个元素。

 $(document).ready(function (){
    $('.submitJobform').on('submit', function(e) {
        $( ".required" ).each(function( index ) {
            if( !$(this).value ){
               $(this).css('background-color','red');
            }
          });

        e.preventDefault();  //prevent form from submitting
    });
 });

答案 2 :(得分:0)

试试这个:

$('.submitJobform').on('submit', function(e) {
    if( !$('.required').value ){
        $('.required').css('background-color','red');
    }

    e.preventDefault();  //prevent form from submitting
});

或者,如果您有多个班级.required,则可以执行以下操作:

$('.submitJobform').on('submit', function(e) {
    $('.required').each(function() {
        if( !$(this).value ){
            $(this).css('background-color','red');
        }
    });

    e.preventDefault();  //prevent form from submitting
});

答案 3 :(得分:0)

在您的代码中,this变量属于表单,因为表单已提交,因此函数被调用。要检查输入,您需要查看它们:

$(document).ready(function (){
    $('.submitJobform').on('submit', function(e) {

        // here this is the form
        $(this).find('.required').each(function() {
            // here this is the current element matched in the each loop
            var input = $(this);

            if (!input.val()) input.css('background-color','red');
        });

        e.preventDefault();  //prevent form from submitting
    });
 });

答案 4 :(得分:0)

引用OP:

  

通常我只会使用jQuery验证插件但不幸的是   在这种情况下不能使用它,因为不需要错误消息,只是   造型改变。“

使用jQuery Validation插件时,您可以轻松关闭验证消息。只需在return false回调函数中放置errorPlacement即可终止消息。然后根据需要使用CSS设置.error类的样式。

$(document).ready(function() {

    $('.submitJobform').validate({
        // rules, options & callbacks,
        errorPlacement: function() {
            return false;
        }
    });

});

DEMO http://jsfiddle.net/eKbmZ/1/