使用 jQuery 为输入字段添加值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18655295/
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
Adding value to input field with jQuery
提问by user966582
I want to add some value in an input field with jQuery. The problem is with the ID of the input field. I am using the id such as options[input2]
. In that case my code does not work. If I use ID like input2
, then it works fine. I need to use options[input2]
, how can I fix the code?
我想用 jQuery 在输入字段中添加一些值。问题在于输入字段的 ID。我正在使用诸如options[input2]
. 在这种情况下,我的代码不起作用。如果我使用 ID like input2
,那么它工作正常。我需要使用options[input2]
,我该如何修复代码?
HTML:
HTML:
<div>
<h3>Working</h3>
<input id="input1" type="text" value="" />
<input class="button" type="button" value="Add value" />
</div>
<div>
<h3>Not working</h3>
<input id="options[input2]" type="text" value="" />
<input class="button" type="button" value="Add value" />
</div>
jQuery:
jQuery:
$('.button').click(function(){
var fieldID = $(this).prev().attr("id");
$('#' + fieldID).val("hello world");
});
Demo:
演示:
回答by Dipesh Parmar
回答by Satpal
回答by Oskar Hane
You have to escape [
and ]
.
Try this:
你必须逃脱[
和]
。尝试这个:
$('.button').click(function(){
var fieldID = $(this).prev().attr("id");
fieldID = fieldID.replace(/([\[\]]+)/g, "\");
$('#' + fieldID).val("hello world");
});
回答by Salione
$.each(obj, function(index, value) {
$('#looking_for_job_titles').tagsinput('add', value);
console.log(value);
});