wmitchell
wmitchell

Reputation: 5725

jquery selector for an element that needs escaped

I have the following element which is generated by some struts code which I am unable to change.

<input type="hidden" name="versions[0].elements[0].description">

I would typically use something like $('input[name=XXX]');

However as my name has special characters I need to be able to escape it. Any ideas?

Thanks W

Upvotes: 1

Views: 135

Answers (5)

Swarne27
Swarne27

Reputation: 5737

Use two backslashes before each special character.

e.g.

$('input[name=\\XXX\\]')

Upvotes: 0

Leo Cai
Leo Cai

Reputation: 610

Idea 1: add a css class to your input element, for example:

<input type="hidden" name="versions[0].elements[0].description" class="version-desc">

Then, to get it:

var $inputs = $("input.version-desc");

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337560

You just need to wrap the name variable in quotes, like this:

$('input[name="versions[0].elements[0].description"]');

Example fiddle

You don't need to escape in this case the attribute value is treated by jQuery internally as a string literal.

Upvotes: 2

Thijs Kramer
Thijs Kramer

Reputation: 1117

From the jQuery API documentation:

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \

So in your case:

$('input[name="versions\\[0\\].elements\\[0\\].description"]');

Upvotes: 1

anacarolinats
anacarolinats

Reputation: 667

if you have a pattern in the input name, you can use the ^= to select name that start with something or $= to select the end or *= to select the input that contains something. For instance:

 $('input[name$="description"]')

select the input that name end with description.

Upvotes: 0

Related Questions