user1355300
user1355300

Reputation: 4987

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/

Upvotes: 1

Views: 18943

Answers (3)

fujy
fujy

Reputation: 5274

try this:

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

Upvotes: 1

Kiran
Kiran

Reputation: 20293

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

Upvotes: 2

adeneo
adeneo

Reputation: 318342

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 ?

Upvotes: 4

Related Questions