5

The name of my form field is contact[0][state] and I'm trying to reference it via jquery to set a default value, but it's not working and I'm wondering if it's not working because of the brackets?

I'm trying:

$('input[name=concat[0][state]]').val('NY');

2 Answers 2

14

nevermind, you are missing quotes (").

try this:

$('input[name="concat[0][state]"]').val('NY');

I know the brackets would be a problem as an ID, but as a property it should work just fine as long as they are in quotes.

adding more info, you could also escape the brackets, but youy must still keep them in quotes.

$('input[name="concat\\[0\\]\\[state\\]"]').val('NY');
Sign up to request clarification or add additional context in comments.

Comments

1

You need to double-escape the braces:

$("input[name=concat\\[0\\]\\[state\\]]").val('');

Edit: this appears to be broken in jQuery 1.4.4, but it works in 1.4.3.

14 Comments

that'd be the case if it was an ID, but as a value of a property it should be fine if its enclosed in quotes.
@Victor: brackets aren't valid in IDs, whether they're escaped or not. This almost certainly will work, but I wasn't sure exactly how good the jQuery selector parser is to feel confident recommending quotes as the solution.
@Andy Can you provide a demo? It doesn't seem to work: jsfiddle.net/P5Pef
How about docs: "If you wish to use any of the meta-characters ( such as !"#$%&'()*+,./:;?@[]^`{|}~ ) as a literal part of a name, you must escape the character with two backslashes: \\." EDIT: Seems like it should work according to the docs. Strange.
@patrick, @Šime: Looks like double-escaping is broken in 1.4.4!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.