Send multiple ` as a list of values I guess, so I can pick it up inside a `foreach` loop with PHP – David Jul 10 '12 at 21:13

2 Answers2

5

First of all you have to use classes for your selects instead of an id. jQuery will only return one element when you use an id. After that the following function will convert all values of the selects you give as paramater as an array.

/**
 * Convert select to array with values
 */    
function serealizeSelects (select)
{
    var array = [];
    select.each(function(){ array.push($(this).val()) });
    return array;
}

So:

var course_ids = serealizeSelects($('.course_id'));

Should for example return:

[1,3,2]
Lumocra
  • 545
  • 2
  • 6
  • 16
  • Thank you. So, after I have created the variable for `plan_ids` (you called it course_ids) how do I send this with jQuery POST? Please describe using my code in the original question! – David Jul 10 '12 at 21:47
  • Like this: `var plan_ids = serealizeSelects($('.plan_id')); $.post('../update.php', { plan_ids: plan_ids }, ...` – Lumocra Jul 10 '12 at 21:55
  • Thank you, It work's now! Now I only need to figure out how to collect the values inside my update.php – David Jul 10 '12 at 22:03
  • In case of the example above, in your PHP `$_POST['course_ids']` will hold: `array(1,3,2)` – Lumocra Jul 10 '12 at 22:18
3

I would give every select element a unique name, an array would also do well here, see this example:

$('#selected > tbody:last').append('<tr><td><select id=\'plan_id\' name="my_select[]"><option value=\'1\'>One</option><option value=\'2\'>Two</option><option value=\'3\'>Three</option></select></td></tr>');

and then just serialize the form before you send it in:

var my_data = $("form").serialize();
...

Edit: The complete example:

$("#add").click(function() {
    $('#selected > tbody:last').append('<tr><td><select id=\'plan_id\' name="my_select[]"><option value=\'1\'>One</option><option value=\'2\'>Two</option><option value=\'3\'>Three</option></select></td></tr>');
    });
                                                                      ^^^^^^^^^^^^^^^^^^^

and:

$('#course_update').click(function() {

var my_data = $("form").serialize();

$('#update_status').html('<img src="../images/ajax-loader.gif" />');
$.post('../update.php', my_data, function(data) {
    $('#update_status').html(data);
    return false;
 });
});
jeroen
  • 91,079
  • 21
  • 114
  • 132
  • I follow you, however I am unable to make it work inside my code. Would you mind providing me with your code, inside mine as posted in the original question? Thank's in advance. – David Jul 10 '12 at 21:54