简体   繁体   English

jQuery更改空的必需输入的背景颜色

[英]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' 必填字段具有一个名为“ 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: 您可以在此处使用.each()遍历所有.required元素:

$('#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'); .filter()所有值为''的元素,然后是appy .css('background-color', '#FF0000'); to filtered elements. 过滤的元素。

To reset colors use .css('background-color', '#fff') 要重置颜色,请使用.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/ 工作小提琴http://jsfiddle.net/sV8QG/

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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