Mostafa King Mostafa King - 1 month ago 7
Javascript Question

return the values of multiple ( multiple select )

i have a dynamic form that duplicate itself for bulk insertion .

example : my form has multiple select

<select name="type[]" multiple>
<option>1</option>
<option>2</option>
<option>3</option>
</select>


when I duplicate it like this

<select name="type[]" multiple>
<option>1</option>
<option>2</option>
<option>3</option>
</select>

<select name="type[]" multiple>
<option>1</option>
<option>2</option>
<option>3</option>
</select>


and select for example all of the options in the two selects it return something like

Array
(
[0] => 1
[1] => 2
[2] => 3
[4] => 1
[5] => 2
[6] => 3
)


with this . i don't know what is selected in the first select and what is selected in the 2nd one
how can i do that

---- EDIT -----

i dublicate the form by jqyery when click on input

jQuery("body").on("click", '.duplicate', function(){

$(".newform"). append(jQuery(".form").html());
return false;

});


where the button that duplicate has class (.duplicate)
and the form in div has class (.form)
and have empty div has class (.newform)

when i click Button (.duplicate) it duplicate the (.form) into ( .newform )

----- EDIT ------

i modified the javascript to fit the accepted answer

jQuery("body").on("click", '.duplicate', function(){
$key = $(".newform>div").length;
$(".newform"). append(jQuery(".form").html().replace(new RegExp('\\[\\]\\[\\]', 'g'),'['+$key+'][]'));
});


i just counted the div inside the (.newform) to make it as a key
then replace every [][] to []['key']

Answer

If you need them to have the same name, always, you can do this:

<?php

    if (isset($_POST['type']))
        var_dump($_POST['type']);
?>
<form method="POST">

    <select name="type[1][]" multiple>
     <option>1</option>
     <option>2</option>
     <option>3</option>
    </select>

    <select name="type[2][]" multiple>
     <option>1</option>
     <option>2</option>
     <option>3</option>
    </select>
    <input type="submit" value="Send"/>
</form>

They will become a multidimensional array in the server side.

Result for all options selected:

array (size=2)
  1 => 
    array (size=3)
      0 => string '1' (length=1)
      1 => string '2' (length=1)
      2 => string '3' (length=1)
  2 => 
    array (size=3)
      0 => string '1' (length=1)
      1 => string '2' (length=1)
      2 => string '3' (length=1)