blue-sky
blue-sky

Reputation: 53806

Select custom values with wildcard

In this fiddle I'm attempting to select the attribute values. So elems var should contain the values listen,submitClicked & listen,textEntered

http://jsfiddle.net/adrianfiddleuser/g2Rxc/128/

source :

<input tag="listen,submitClicked" id="click" type="submit" value="click"/>
<input tag="listen,textEntered" id="test" type="textbox" value="test"/>

var elems = $('p[^listen]')

console.log(elems)

But wildcard does not seem to be working. How to select custom values that begin with "listen" and add these values to an array ?

Upvotes: 0

Views: 237

Answers (2)

Pevara
Pevara

Reputation: 14310

As @JamesDonnelly correctly noted the tag attribute is in fact invalid (though it will work). Also, working with comma separated values in your attribute values will make things harder once you start expanding your js.

From what I understand from your example, I think it would be better to structure your HTML as follows:

<input data-listen="submitClicked" id="click" type="submit" value="click"/>
<input data-listen="textEntered" id="test" type="textbox" value="test"/>

Selecting all elements that "listen" would be as easy as:

$('[data-listen]');

And it would also be a lot easier to check for elements that listen for something specific, or find out what each element listens for, without having to parse the strings in that tag attribute of yours.

$('[data-listen]').each(function() {
    console.log('I listen for ' + $(this).data('listen'));
});
var $listensForSubmit = $('[data-listen="submitClicked"]');

Upvotes: 0

James Donnelly
James Donnelly

Reputation: 128791

You're not using the ^= attribute selector correctly. You'd need to specify the tag attribute:

p[tag^=listen]

[att^=val]

Represents an element with the att attribute whose value begins with the prefix "val". If "val" is the empty string then the selector does not represent anything.

W3C's Selectors Level 3

Furthermore, tag isn't a valid HTML attribute, and you may want to consider using a data-* attribute instead.

Upvotes: 2

Related Questions