2

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.

1
  • trigger the keyup event when changing the value with the other methods. Commented May 6, 2013 at 19:35

1 Answer 1

3

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");
    }
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.