0

On button click, I'm checking if any input with the class 'req' is empty. I want to change the border of only the empty inputs to red. Here is my code.

$('#btnUpdateOrder').click(function () {
        if ($('.req').attr('value').trim() == '') {
            $(this).css('border', '1px solid red');
            alert('All fields in the ship to and bill to areas must be completed');
            return false;
        }
    });

But my code makes the button's border red, not the input. Any help would be appreciated.

4
  • 1
    You should never use .attr('value') but rather .val() to get the value. Commented Feb 15, 2012 at 21:11
  • Actually, .val() doesn't work with text boxes. Commented Feb 15, 2012 at 21:18
  • @boruchsiper - Yes, it does. It should work with any element that supports the value attribute. Commented Feb 15, 2012 at 21:22
  • I admit I was wrong. Thanks for pointing out. Commented Feb 15, 2012 at 21:27

2 Answers 2

1

this refers to the button. You could use filter to reduce the matched set of elements to those that are empty and then apply the CSS to that set:

$(".req").filter(function() {
    return $.trim(this.value) === "";
}).css("border", "1px solid red");

Note that I've used the jQuery trim function because the native function is not available in older browsers.

Sign up to request clarification or add additional context in comments.

Comments

0

Simply use $('.req') instead of $(this):

$('#btnUpdateOrder').click(function() {
    $('.req').filter(function() {
        return $(this).val().trim() == '';
    }).css("border", "1px solid red");
});

1 Comment

I would do that, except this will make all the inputs with class 'req' have a red border. I need only for the empty inputs to have the red border. Thanks for trying.

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.