Tom Hubbard
Tom Hubbard

Reputation: 16139

Can I select elements with a set of attribute values?

Is there a way to refactor something like this:

$("input[name='InputName1'],input[name='InputName2']").val("");

into something like this:

$("input[name='InputName1|InputName2']").val("");

Essentially, is it possible to select elements based on a set of attribute values without the repetitive parts of the selector?

Upvotes: 0

Views: 134

Answers (7)

Mutation Person
Mutation Person

Reputation: 30530

As well as giving the inputs a class (as suggested in another answer to this question) is it possible that the imputs have an inherent logical grouping within the DOM? (e.g. all in cells within a table, or all within a certain div).

Rather than give them a class, you could select them by their logical DOM grouping, and if possible add an ID somewhere along the way to speed up the selector performance.

If possible try to avoid selection by class (although the example elsewhere mitigates their performance hit by looking for them in conjuntion with the input element)

Upvotes: 1

nikc.org
nikc.org

Reputation: 16993

You can use the attribute contains selector $('input[name*=InputName]') for matching a substring in an attribute value. Although, perhaps a common rel-attribute or classname would be a better way to go. But that's subjective, I suppose.

Upvotes: 0

redsquare
redsquare

Reputation: 78687

You can use the starts with selector

$("input[name^=InputName]")

My preferred option would be a class however as it performs better.

Upvotes: 1

kkyy
kkyy

Reputation: 12470

You can always write a custom selector, if there isn't one by default :)

In fact, you can use the example from the linked page almost directly...

Upvotes: 0

Tomalak
Tomalak

Reputation: 338416

The answer to this question shows that (with the help of another plugin) you could do this:

$('input:regex(name, InputName[12])')

Upvotes: 1

cletus
cletus

Reputation: 625467

The first version you have is about as short as it gets, ignoring the special case:

$("input[name^=InputName]")

I say special case because if you want arbitrary names it's not like they're going to have that convenient prefix all the time (I would assume).

Generally I try and avoid attribute selectors. I usually feel like I've failed if I have to resort to them. Try and use marker classes where possible so instead of:

$("input[name='InputName1'],input[name='InputName2']").val("");

you give them both a class of "reset" and do:

$("input.reset").val("");

Upvotes: 1

smack0007
smack0007

Reputation: 11356

Maybe you could give the inputs a class? Then you could just use $('input.clearMe').

Upvotes: 4

Related Questions