jquery - reference input by name?

2019-03-30 06:52发布

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条回答
SAY GOODBYE
2楼-- · 2019-03-30 07:17

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.

查看更多
唯我独甜
3楼-- · 2019-03-30 07:20

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');
查看更多
登录 后发表回答