L. Grunn L. Grunn - 6 months ago 14
jQuery Question

How to get all the values in a select list with a AJAX request?

I'm passing the selected values of my dropdown list with the following code:

function getData(){
//Variabelen die worden gehaald uit de gekozen dropdown selecties
$('#slctTable, #slctField, #slctAttribute').change(function ()
{
//var fieldvalues = fieldValues;
var tableSelected = document.getElementById("slctTable").value;
var fieldSelected = document.getElementById("slctField").value;
var attributeSelected = document.getElementById("slctAttribute").value;
$.ajax({
"url": "php/getData.php",
"type": "GET",
"data": {
//fieldValues: fieldValues,
tableSelected: tableSelected,
fieldSelected: fieldSelected,
attributeSelected: attributeSelected
},
success: function(data){
// mapData(data);
}
})
});
};


But now I want to get al the values of the select lists and pass them in the variables: tableList, fieldList and attributeList. Can i do that the same way as I did with the selected values?

Jai Jai
Answer

Event bindings in a function call is not a good way to bind an event, it can lead to multiple bindings. Better to do this in the doc ready block.

But now I want to get al the values of the select lists and pass them in the variables: tableList, fieldList and attributeList. Can i do that the same way as I did with the selected values?

function allValues(el) {
  var arr = $('option', el).map(function(i, v) {
    return this.value;
  }).get();

  return arr;
}
$('#slctTable, #slctField, #slctAttribute').change(function() {
  //var fieldvalues = fieldValues; 
  var tableSelected = document.getElementById("slctTable").value;
  var fieldSelected = document.getElementById("slctField").value;
  var attributeSelected = document.getElementById("slctAttribute").value;
  var tableList = allValues($('#slctTable'));
  var fieldList = allValues($('#slctField'));
  var attributeList = allValues($('#slctAttribute'));
  $.ajax({
    "url": "php/getData.php",
    "type": "GET",
    "data": {
      //fieldValues: fieldValues, 
      tableSelected: tableSelected,
      fieldSelected: fieldSelected,
      attributeSelected: attributeSelected,
      tableList: tableList,
      fieldList: fieldList,
      attributeList: attributeList
    },
    success: function(data) {
      // mapData(data);
    }
  })
});
Comments