Marco Lisei Marco Lisei - 5 months ago 10
JSON Question

jQuery function to read JSON data. parameter to populate a select

the title may be not very clear but this is what I need to do.
I have these 2 JSON files:

?({
Makes:[
{
"make_id":"ac",
"make_display":"AC",
"make_is_common":"0",
"make_country":"UK"
},
{
"make_id":"acura",
"make_display":"Acura",
"make_is_common":"1",
"make_country":"USA"
},
{etc...}
]});


and

?({
Models:[
{
"model_name":"Escape",
"model_make_id":"ford"
},
{
"model_name":"Excursion",
"model_make_id":"ford"
},
{etc...}
]});


I want to populate 2 selects:

<select id= "dropDownDest">
</select>
<select id= "dropDownDest2">
</select>


with a function like these:

CreateSelectFromJson(jsonMakesUrl,"#dropDownDest","Makes","make_id","make_display");
CreateSelectFromJson(jsonModelsUrl,"#dropDownDest2","Models","model_name","model_name");


I did something like this, but can't figure out how to pass the last 3 parameters.
This function is only working for Models where I've written the parameters inside the function (they are: data.Models where Models needs to be replaced by nodo and val(value.model_name).text(value.model_name) by parameter1 and parameter2).

function CreateSelectFromJson(jsonfromurl,idselect,nodo,parameter1,parameter2){
appendSelectLoader(idselect,"Caricamento..."); //aggiunge un option con il caricamento
$.getJSON(jsonfromurl,function(data)
{
$(idselect + " option").remove();
$(idselect).prop( "disabled", false );
$.each(data.Models,function(key,value)
{
var option = $('<option />').val(value.model_name).text(value.model_name);
$(idselect).append(option);
});

});
}

function appendSelectLoader(idselect,testo) {
$(idselect).prop( "disabled", true );
var option = $('<option />').val("").text(testo);
$(idselect).append(option);
}

Answer

You need to get the values of your json file, like this

function CreateSelectFromJson(jsonfromurl, idselect, nodo, parameter1, parameter2) {
  appendSelectLoader(idselect, "Caricamento..."); //aggiunge un option con il caricamento
  $.getJSON(jsonfromurl, function(data) {
    $(idselect + " option").remove();
    $(idselect).prop("disabled", false);
    $.each(data[nodo], function(key, value) {
      var option = $('<option />').val(value[parameter1]).text(value[parameter2]);
      $(idselect).append(option);
    });

  });
}

function appendSelectLoader(idselect, testo) {
  $(idselect).prop("disabled", true);
  var option = $('<option />').val("").text(testo);
  $(idselect).append(option);
}

$(document).ready(function() {

  CreateSelectFromJson('Makes.json', "#dropDownDest", "Makes", "make_id", "make_display");
  CreateSelectFromJson('Models.json', "#dropDownDest2", "Models", "model_name", "model_name");

});

See the Plunker

Comments