tags:

views:

62

answers:

7

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?

+4  A: 

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

smack0007
+1  A: 

You can use the starts with selector

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

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

redsquare
should be ^= according to docs
Zed
yes yes typo !:)
redsquare
+1  A: 

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("");
cletus
+1  A: 

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

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

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...

kkyy
A: 

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.

nikc
+1  A: 

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)

James Wiseman