1

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/

2
  • Please care to explain what do you really want to "add" into "what value"? It's not working because you are setting a static value "value+" Commented Sep 2, 2013 at 17:33
  • @Kampai i just used a static value in above example. Idea is to pass multiple strings in a hidden input field to store in db. I got the answers below but thanks. Commented Sep 2, 2013 at 17:43

3 Answers 3

4

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 ?

Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

1

try this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.