Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery, how do you mimic the form serialization for a select with multiple options selected in a $.ajax call?

Tags:

jquery

Below is my $.ajax call, how do I put a selects (multiple) selected values in the data section?

$.ajax({
    type: "post",
    url: "http://myServer" ,
    dataType: "text",
    data: {
        'service' : 'myService',
        'program' : 'myProgram',
        'start' : start,
        'end' : end ,
        },
    success: function(request) {
      result.innerHTML = request ;
    }   // End success
  }); // End ajax method

EDIT I should have included that I understand how to loop through the selects selected options with this code:

$('#userid option').each(function(i) {
 if (this.selected == true) {

but how do I fit that into my data: section?

like image 870
Jay Corbett Avatar asked Oct 12 '08 03:10

Jay Corbett


2 Answers

how about using an array?

data: {
    ...
    'select' : ['value1', 'value2', 'value3'],
    ...
},

edit: ah sorry, here's the code, a few caveats:

'select' : $('#myselectbox').serializeArray(),

in order for serializeArray() to work though, all form elements must have a name attribute. the value of 'select' above will be an array of objects containing the name and values of the selected elements.

'select' : [
    { 'name' : 'box', 'value' : 1 },
    { 'name' : 'box', 'value' : 2 }
],

the select box to produce the above result would be:

<select multiple="true" name="box" id="myselectbox">
   <option value="1" name="option1" selected="selected">One</option>
   <option value="2" name="option2" selected="selected">Two</option>
   <option value="3" name="option3">Three</option>
</select>
like image 187
Owen Avatar answered Oct 20 '22 01:10

Owen


Thanks to the answer from @Owen, I got this code to work.

For a select box with an id="mySelect" multiple="true"

    var mySelections = [];
    $('#mySelect option').each(function(i) {
        if (this.selected == true) {
            mySelections.push(this.value);
        }
    });


    $.ajax({
      type: "post",
      url: "http://myServer" ,
      dataType: "text",
      data: {
        'service' : 'myService',
        'program' : 'myProgram',
        'selected' : mySelections
        },
      success: function(request) {
        result.innerHTML = request ;
      }
    }); // End ajax method
like image 21
Jay Corbett Avatar answered Oct 19 '22 23:10

Jay Corbett