undefined is our god
undefined is our god

Reputation: 511

Find elements which contains part of an attribute

I'm having some trouble to find a selector which can match the following:

$("input[data-rule-*]");

So, if i have data-rule-required or data-rule-email, both of the attributes need to be matched. (only examples, i have a bunch of suffixes, specify all of them is not an option).

I've found only $("#element[attribute=value]") selectors, which doesn't satisfy my condition.

I took a look at this topic: how do I find elements that contain a data-* attribute matching a prefix using jquery. The question is the same, but i'd like to know if there's a more compact solution.

HTML example. Assuming that i can have a lot more inputs with distinct data-rule-something attributes:

<div>
    <label for="field1" class="control-label">Field 1</label>
    <input maxlength="4" data-inputmask="'mask':'9999'" data-rule-required="true" id="field1" type="text" class="form-control" placeholder="0123"></input>
</div>
<div>
    <label for="field2" class="control-label">Conta Corrente</label>
    <input maxlength="14" data-rule-range="5,10" data-inputmask-regex="[0-9]{14}" id="field2" type="text" class="form-control" placeholder="0123456"></input>
</div>
<div>
    <label for="field3"></label>
    <input maxlength="2" data-rule-email="true" data-inputmask-regex="[a-zA-Z0-9]{2}" id="field3" type="text" class="form-control text-uppercase" placeholder="00"></input>
</div>

Upvotes: 0

Views: 99

Answers (2)

sinisake
sinisake

Reputation: 11318

One not so elegant way, but it seems that it is working:

$("input").filter(function() {

   if(Object.keys($(this).data()).toString().indexOf('rule')!==-1) {

    return $(this);
   }
}).css('background-color','red');

Demo: http://jsfiddle.net/8x05bh2v/

Upvotes: 1

Thriggle
Thriggle

Reputation: 7049

Your options are either to add another attribute or identifier to the elements so you can select them all, or to include all the attribute combinations in your query selector.

The example below adds an additional data-object singleton to the two input elements, then queries for that attribute to update the field values.

var dataObjects = document.querySelectorAll("[data-object]");
for(var i = 0, len = dataObjects.length; i < len; i++){
  dataObjects[i].value = i;
}
<input type="text" data-rule-required data-object />
<input type="text" data-rule-email data-object />

Upvotes: 2

Related Questions