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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 12:27:23  来源:igfitidea点击:

Add multiple values in input field with jQuery

javascriptjquery

提问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+");   
});

Demo:http://jsfiddle.net/D97bV/

演示:http : //jsfiddle.net/D97bV/

回答by adeneo

You add strings together with +

您将字符串添加到一起 +

$("button").on('click', function(e) {
    e.preventDefault();
    var elem = $(this).parent().find('input[name=myinput\[\]]');

    elem.val( elem.val() + 'add this' );
});

FIDDLE

小提琴

Now you only need something useful to add ?

现在你只需要添加一些有用的东西?

回答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+");

});

DEMO FIDDLE

演示小提琴

回答by fujy

try this:

试试这个:

$("button").click(function(e) {
    e.preventDefault();
    var myInput = $(this).parent().find('input[name=myinput\[\]]');
    myInput.val(myInput.val() + "value+");   
});