I have this jQuery code to add<select>
elements in a table row with an “add” button:
$("#add").click(function() { $('#selected > tbody:last').append('<tr><td><select id='plan_id'><option value='1'>One</option><option value='2'>Two</option><option value='3'>Three</option></select></td></tr>'); });
What do I need to modify in the below code to be able to POST multiple values from the select elements as an array? Right now it only inserts one value at the time to my MySQL database.
$('#course_update').click(function() { var course_id = $('#course_id').val(); var plan_id = $('#plan_id').val(); var price_id = $('#price_id').val(); var course_name = $('#course_name').val(); var course_isActive = $('#course_isActive').val(); var course_city_id = $('#course_city_id').val(); $('#update_status').html('<img src="../images/ajax-loader.gif" />'); $.post('../update.php', { course_id: course_id, plan_id : plan_id, price_id: price_id, course_name: course_name, course_city_id: course_city_id, course_isActive: course_isActive }, function(data) { $('#update_status').html(data); return false; }); });
Advertisement
Answer
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]