boruchsiper
boruchsiper

Reputation: 2028

Determine which input with class is empty

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.

Upvotes: 0

Views: 36

Answers (2)

ThiefMaster
ThiefMaster

Reputation: 318488

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

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

Upvotes: 0

James Allardice
James Allardice

Reputation: 165951

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.

Upvotes: 1

Related Questions