Dormouse
Dormouse

Reputation: 5198

Is there a way to select all elements with a certain property value?

I'm building a fairly simple plugin with jQuery that validates a form. When an element is assessed to be valid I run

$(this).prop("valid", false);

In certain instances I'm going to want to block the form from submitting if anything is invalid. Essentially I'm looking for a way to select all the elements where the valid property is false? Am I going to have to iterate over all relevant elements and check for a false reading or is there a jQuery selector that I've overlooked? Something like:

$("input[valid=false]");

Would be nice. Any suggestions?

Upvotes: 4

Views: 613

Answers (3)

xkeshav
xkeshav

Reputation: 54016

use this:

$(':input').each( function() {
   return $(this).prop('valid');
});

Upvotes: 0

Robert Koritnik
Robert Koritnik

Reputation: 105029

Reusable :invalid jQuery selector filter

You could write a simple selector filter:

$.extend($.exp[":"], {
    invalid: function(element) {
        return element.valid === false;
    }
});

Then simply combine it with whatever selector your using to get your elements ie:

// all invalid inputs
$(":input:invalid");
// or all invalid text boxes
$("input[type=text]:invalid");

That's it.

Let's put it all in a simple plugin that you can easily include in your script code or put in a script file (for reusability purposes on several pages as well as several applications if you'd use the same validation functionality):

(function($) {

    $.extend($.exp[":"], {
        invalid: function(element) {
            return element.valid === false;
        }
    });

})(jQuery);

Upvotes: 5

alex
alex

Reputation: 490223

Try this...

$('input').filter(function() {
   return this.valid === false; 
});

It will return all input elements (do you mean :input?) where its valid property is false (notice strict equality comparison).

Upvotes: 5

Related Questions