charlie
charlie

Reputation: 481

jquery `$form.find` get element inside form

I have this JQuery code:

if ($form.find('.required').filter(function(){ return this.value === '' }).length > 0) {

}

within this if statement, how can i get each element and add a class to it?

i tried $(this).addClass("EmptySelect"); but it just adds the class to the form itself and not the element

Upvotes: 0

Views: 964

Answers (1)

AmmarCSE
AmmarCSE

Reputation: 30567

Perform addClass right after the filter() call

    var emptyElements = $form.find('.required').filter(function() {
        return this.value === ''
    });
    if (emptyElements.length > 0) {
        emptyElements.addClass("EmptySelect");
    }

However, you can just connect the filter statement with addClass without the if since filter will only return the empty elements

$form.find('.required').filter(function() {
            return this.value === ''
        }).addClass("EmptySelect");

Upvotes: 1

Related Questions