Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery Select all elements with data attribute common name [duplicate]

I'm trying to use jQuery to select all the inputs in my form that have a data attribute with a similar name.

This is my form:

<form id = "myForm">
  <input name="name" data-valid-presence=true >
  <input name="age" data-valid-biggerThan="18" >
  <input name="email[0]" data-valid-email=true >
  <input name="email[1]" data-valid-email=true >
</form>

and my jQuery selector is:

var inputs = jQuery("#myForm").find("input[data-valid-email],[data-valid-length],[data-valid-presence], [data-valid-biggerThan]");

I'm looking for a way to select all the inputs that have a data-valid-* in them without having to find them one by one like this.

Any ideas?

like image 958
Yoav Yogi Grosman Avatar asked Nov 13 '22 01:11

Yoav Yogi Grosman


1 Answers

You can use jQuery.filter:

var inputs = $('form').find('input').filter(function() {
    var matched = false;
    $.each(this.attributes, function(attr) {
        if ( matched ) return;
        matched = /^data-valid/.test(this.name);
    });
    return matched;
});
like image 94
kalley Avatar answered Nov 15 '22 00:11

kalley