簡體   English   中英

使用 jQuery 向輸入字段添加值

[英]Adding value to input field with jQuery

我想用 jQuery 在輸入字段中添加一些值。 問題在於輸入字段的 ID。 我正在使用諸如options[input2]類的 ID。 在這種情況下,我的代碼不起作用。 如果我使用 ID 之類的input2 ,那么它工作正常。 我需要使用options[input2] ,我該如何修復代碼?

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:

$('.button').click(function(){
    var fieldID = $(this).prev().attr("id");
    $('#' + fieldID).val("hello world");
});

演示:

http://jsfiddle.net/4XR8M/

您可以按照以下方式進行。

$(this).prev('input').val("hello world");

現場演示

你可以簡單地使用

 $(this).prev().val("hello world");

JSFiddle 演示

你必須逃脫[] 試試這個:

$('.button').click(function(){
    var fieldID = $(this).prev().attr("id");
    fieldID = fieldID.replace(/([\[\]]+)/g, "\\$1");
    $('#' + fieldID).val("hello world");
});

演示: http : //jsfiddle.net/7RJtf/1/

$.each(obj, function(index, value) {
    $('#looking_for_job_titles').tagsinput('add', value);
    console.log(value);
});

你可以簡單地使用$(this).prev().val("hello world");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM