I have a div containing 3 input fields and a button. When the button is clicked, my js launched. My JS checks for input that have empty values and puts them with a red background. Everything working fine. My problem is as follows. Lets imagine the following situation: I just input the the 2 first input fields and click on the button. What will happen is that the third input will become red. Normal. But when I then put some text into that third input and reclick the button it is not switching to red. I don't get it. Hope someone can help. Thank you in advance for youe replies. Cheers. Marc.
My html:
<div id="userList">
<input type="text" id="user1" class="verif" /><br>
<input type="text" id="user2" class="verif" /><br>
<input type="text" id="user3" class="verif" /><br>
<input type="submit" id="btn" />
</div>
My js:
$('#btn').click(function() {
var myArray = [];
var userList = $('#userList .verif');
userList.each(function() {
var userID = $(this).attr('id');
var userName = $(this).val();
if (!userName) {
myArray.push({
'id': userID,
'name': userName
});
}
});
$.each(myArray, function(i, v) {
$('#userList .verif[id=' + v.id + ']').css('background-color', 'red');
});
});
You are not removing the background color for valid fields. You can simplify this whole thing into one chained statement:
Example: http://jsfiddle.net/eKwJn/