javascript 使用 jQuery 在输入字段中添加多个值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18578270/
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
Add multiple values in input field with jQuery
提问by user1355300
I want to add multiple input values in an input field with jQuery. So that everytime I hit the button, a new value is added in the same field along with the old value.
我想使用 jQuery 在输入字段中添加多个输入值。这样每次我点击按钮时,都会在同一字段中添加一个新值以及旧值。
I am trying following code, but it does not add the value, it simply overwrites the previous value.
我正在尝试以下代码,但它没有添加值,它只是覆盖了以前的值。
HTML:
HTML:
<div class="wrap">
<button>Add value</button>
<input name="myinput[]" value="" />
</div>
jQuery:
jQuery:
$("button").click(function(e) {
e.preventDefault();
$(this).parent().find('input[name=myinput\[\]]').val("value+");
});
回答by adeneo
回答by Unknown
Try:
尝试:
$("button").click(function(e) {
e.preventDefault();
var val = $(this).parent().find('input[name=myinput\[\]]').val();
$(this).parent().find('input[name=myinput\[\]]').val(val+"value+");
});
回答by fujy
try this:
试试这个:
$("button").click(function(e) {
e.preventDefault();
var myInput = $(this).parent().find('input[name=myinput\[\]]');
myInput.val(myInput.val() + "value+");
});