Reputation: 43
I am making a web app where a user must type several mandatory text fields. To notify the user of this, it is stated that he/she must type in all the pink text fields. I gave them pink backgrounds through this: (notice that I am using the jQuery UI spinner widget)
$('input[type="text"]').spinner({min: 0}).css("background-color", "pink");
What I am trying to do, is change the background color to white when the user types in the field. I did this:
$('input[type="text"]').keyup(function () {
if ($(this).val().length !== 0) {
$(this).css("background-color", "white");
} else{
$(this).css("background-color", "pink");
}
});
This works well, but I am also using a spinner (and a slider) to change the value of the text field. To do that I typed this up:
$(document).click(function () {
if ($('input[type="text"]').val().length !== 0) {
$('input[type="text"]').css("background-color", "white");
} else{
$('input[type="text"]').css("background-color", "pink");
}
});
As you could imagine, this didn't work. If one text field has text in it, then all the text fields turn to white once the document is clicked. I cannot specify which text input I want to target with this. I then tried a .change() jQuery function:
$('input[type="text"]').change(function () {
if ($(this).val().length !== 0) {
$(this).css("background-color", "white");
} else{
$(this).css("background-color", "pink");
}
});
However, this only works after the user clicks out of field, and it does nothing when the value is changed via the spinner or the slider. Any suggestions? PS: I know this was kind of long-winded, but I wanted to give as much information as possible.
Upvotes: 2
Views: 1088
Reputation: 74420
On modern browsers, use oninput
instead: {added other browsers support too}
$('input[type="text"]').on('input DOMAttrModified paste change',function () {
if ($(this).val().length !== 0) {
$(this).css("background-color", "white");
} else{
$(this).css("background-color", "pink");
}
});
Upvotes: 3