2

I have a hidden field in form A.

<input type="hidden" name="item_name[]" id="item_name" />

I want to add multiple values to this field using jQuery on a button click. this value coming from pop up window that just add these values to hidden field .

var name = $('#formid input[name=name1]').val();  
$("#item_name").val(name);

suppose I added values two time "a" and "b" then when I submit the form and print the form values at server side. I get this value

["item_name"]=>
array(1) {
[0]=>
string(2) "ab"
}

how should I proceed to get these value like -

 ["item_name"]=>
 array(2) {
 [0]=>
 string(1) "a",
 [1]=>
 string(1) "b"
 }

2 Answers 2

1

When the user clicks the button, you should append another hidden input to the form, with name="item_name[]" and the value you wish to add:

$('#formid input[name=name1]').each(function(){
    var name = $(this).val();
    $("#item_name").after(
        "<input name='item_name[]' value="+name+" />"
    );
});  

This way, you can add several values instead of just two. The loop in this case might be unnecessary (if you have just one element with name "name1"), but reflects the fact that you could use this with a selector returning more than one element.

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

Comments

1

You need 2 hidden inputs with the same name item_name[] for it to work like you want.

Or you can have something like this

if ($("#item_name").val() == '') {
    $("#item_name").val(name);
} else {
    var value = JSON.parse($("#item_name").val());
    $("#item_name").val(JSON.stringify(value.push(name)));
}

I haven't tested it but with JSON.stringify you could send an array in a single input.

1 Comment

Unexpected token aa. "aa" is the value I entered when I followed your second approach.

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.