Jquery为输入赋值

Geo*_*tas 12 jquery input

我有以下输入字段

<input type="text" name="location[state_id]" id="location[state_id]" value="" >

我试图用以下jquery分配一个值

$("#location\\[state_id\\]").val("5");
Run Code Online (Sandbox Code Playgroud)

但它不起作用!仅当两者的名称仅为位置时才有效.

谢谢

npc*_*diu 22

作为#一个id选择器,你可以尝试将输入的id设置为有效的CSS id,并让输入的名称相同(我假设这种格式是某种框架所必需的).例如,HTML可能如下所示:

<input type="text" id="location_state_id" name="location[state_id]" value="" />
Run Code Online (Sandbox Code Playgroud)

和jQuery表达式:

$('#location_state_id').val('5');
Run Code Online (Sandbox Code Playgroud)


Sta*_*ble 8

试试这个

<input type="text" name="location[state_id]"class="input" id="location[state_id]" value="" >

$(".input").val("5");
Run Code Online (Sandbox Code Playgroud)

要么

你可以用curt的答案:

$("input[name='location[state_id]'").val("5");


Cur*_*urt 8

如果您希望使用name选择器的一部分,可以使用以下选择器:

$("input[name='location[state_id]'").val("5");
Run Code Online (Sandbox Code Playgroud)

演示