Question

I have a problem maybe you can help me? input is name="name [1]" Is it possible to use:

$('#name[1]').val(myvariable); 

Because the brackets from input name can not be removed, and with them that does not work. ;)

Sorry I wrote with google translate :)

Was it helpful?

Solution

$('#name[1]') would look for an element with an id of name and an attribute [1]. You can try this instead:

$('[name="name\\[1\\]"]').val(myvariable);

This will search for an element with a name = name[1].

FYI, You have to escape the brackets with 2 backslashes like that because you're actually escaping two things. The double backslash "\" escapes to "\" in JavaScript. Then jQuery sees the "[" and escapes the bracket.

OTHER TIPS

If your input has the attribute name set to name[1], then you can select it via;

$('input[name="name\\[1\\]"]').val(myvariable); 

... per the escaping rules for jQuery selectors. Note the lack of the # in the selector. That's the ID selector. If your input has an id of name[1] (e.g. <input id="name[1]" />), use;

$('#name\\[1\\]').val(myvariable); 

You're using a # which is an ID selector. You can select your input using the following selector:

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

In jQuery Selectors documentation have a explanation about this...

http://api.jquery.com/category/selectors/

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

you can do...

$('#name\\[1\\]').val(myvariable); // if is in ID
$('input[name="name[1]"]').val(myvariable); // if is in Name
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top