Jquery 为输入赋值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12886002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery assign value to input
提问by George Pittas
I have the following input field
我有以下输入字段
<input type="text" name="location[state_id]" id="location[state_id]" value="" >
<input type="text" name="location[state_id]" id="location[state_id]" value="" >
and i am trying to assign there a value with the following jquery
我正在尝试使用以下 jquery 分配一个值
$("#location\[state_id\]").val("5");
but it does not working! It works only if the name of both is only location.
但它不起作用!仅当两者的名称都只是位置时才有效。
Thanks
谢谢
回答by npclaudiu
As #
is an id selector, you could try to set the id of the input to a valid CSS id and let the name of the input the same (I assume that this format is required by a framework of some kind). For example, the HTML can look like:
作为#
id 选择器,您可以尝试将输入的 id 设置为有效的 CSS id 并让输入的名称相同(我假设某种框架需要这种格式)。例如,HTML 可能如下所示:
<input type="text" id="location_state_id" name="location[state_id]" value="" />
and the jQuery expression:
和 jQuery 表达式:
$('#location_state_id').val('5');
回答by StaticVariable
try this
尝试这个
<input type="text" name="location[state_id]"class="input" id="location[state_id]" value="" >
$(".input").val("5");
or
或者
you can use curt's answer:
你可以使用curt的回答:
$("input[name='location[state_id]'").val("5");
$("input[name='location[state_id]'").val("5");
回答by Curt
回答by henkieee
JQuery
查询
$('input[name="location[state_id]"]').val(5);