简体   繁体   中英

Add multiple values in input field with jQuery

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.

I am trying following code, but it does not add the value, it simply overwrites the previous value.

HTML:

<div class="wrap">
    <button>Add value</button>
    <input name="myinput[]" value="" />
</div>

jQuery:

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

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

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 ?

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

try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM