2

I would like to when I change #town and #animal value, then inputs background will be red. My code is change the inputs background, when I change one input, but I would like to, if I change both input, after the code will be change the background color.

My code:

<!DOCTYPE html>
<html>
<head>
    <title>Test page</title>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>

    <script>
    $(document).ready(function() {
        $('#town, #animal').on('change', function() {
            $('input').css('background', 'red');
        });
    });
    </script>
</head>
<body>

<input type="text" id="town">
<input type="text" id="animal">

</body>
</html>
1
  • "You would like to change the text input color to red onChange" I get the first part of your question I think. The second part is harder to read. Maybe you want to change the color only if BOTH inputs are changed? Commented Jun 3, 2017 at 12:57

2 Answers 2

5

You can try this Working Fiddle

$('#town, #animal').on('change', function() {
    if($.trim($('#town').val())!='' && $.trim($('#animal').val())!=''){
        $('input').css('background', 'red');
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1

If you're wanting it so that you want to wait until both inputs have changed, then that's pretty simple! :)

Simply, have two variables:

var townChanged = false;
var animalChanged = false;

Then, do two jQuery functions:

$('#town').on('change', function() {
    townChanged = true;
    if (animalChanged) {
        $('input').css('background', 'red');
    }
});

$('#animal').on('change', function() {
    animalChanged = true;
    if (townChanged) {
        $('input').css('background', 'red');
    }
});

Obviously you're going to want to clean it up a bit, but I hope that's a good start for you

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.