问题描述:

I have a form that has both required and non required fields and I want to change the background colour of only the required inputs that are empty when the user submits the form.

The required fields have a class called 'required'

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

if($('.required').val() == '')

{

$('.required').css('background-color' , '#FF0000');

}

});

All this does is if all of the fields are empty it changes all of them but if one isn't it doesn't change any of them.

网友答案:

You can use .each() here to loop through all .required elements:

$('#audit_submit').click(function(){
    $('.required').each(function() {
        if($(this).val() == '') {
           $(this).css('background-color' , '#FF0000');
        }
    });
});
网友答案:

Working fiddle http://jsfiddle.net/sV8QG/

$('p').click(function(){
   if($('.required').val() == '') 
    {
           $('.required').css('background-color' , '#FF0000');
        }
    else{
           $('.required').css('background-color' , 'white');
    }
});
网友答案:

Fiddle Demo

.filter() all the elements whose value is '' and than appy .css('background-color', '#FF0000'); to filtered elements.

To reset colors use .css('background-color', '#fff')

$('#audit_submit').click(function () {
    $('.required').css('background-color', '#fff').filter(function () {
        return $.trim(this.value) === '';
    }).css('background-color', '#FF0000');
});
相关阅读:
Top