简体   繁体   中英

jquery change background colour of empty required inputs

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');
        }
    });
});

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');
});

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM