Reputation: 2415
I am missing something here. Seems like an easy question. I have this:
<form>
<input type="text" name="name" id="name" class="form-control" placeholder="Name" required />
<input type="text" name="address" id="address" class="form-control" placeholder="Address" required />
...
</form>
I want this function to work:
$('#submit').click(function() {
var fields = $('.form-control');
_.each(fields, function(field) {
if( field.value == "" ) {
field.css("background","#FFB6B5");
}
});
});
I get undefined is not a function
on the line:
field.css("background","#FFB6B5");
Is like the field
is not an element. Why this is happening?
Upvotes: 0
Views: 39
Reputation: 133403
As per your code field
refers to underlying DOM element and .css()
is a jQuery function. Thus you need to use jQuery object.
Use
$(field).css("background","#FFB6B5");
You can use .each()
Iterate over a jQuery object, executing a function for each matched element.
Example
$('.form-control').each(function( index ) {
if(this.value == ""){
$(this).css("background","#FFB6B5");
}
});
Upvotes: 2
Reputation: 25525
I would do it like:
$('#submit').click(function() {
$('.form-control').each(function() {
if ($(this).val() === "" ) {
$(this).css("background","#FFB6B5");
} else {
$(this).css("background","#FFF");
}
});
});
Upvotes: 0