kate_hudson kate_hudson - 4 months ago 6
Ajax Question

Populating additional select input after ajax call

I have a select input. When changed, the following is triggered

$('#type').change(function() {
var selectedYear = $("#year option:selected").val();
var selectedProduct = $("#product option:selected").val();
var selectedType = $("#type option:selected").val();
$.ajax({
type: "get",
url: "./report",
data: {
year : selectedYear,
product : selectedProduct,
type : selectedType
}
}).done(function(data){
var url = $('meta[name="base_url"]').attr('content');

$('#displayImage').attr('src', '');
$('#displayImage').attr('src', url + data);
$('#displayImage').css('display', 'block');
});
});


The url it calls triggers a function that essentially fillws up an array with image paths. Once the image array is populated, I do

if(!empty($imageArray)) {
return $imageArray;
}


Now in the done section in my ajax call I display the image. This works fine if the array only has one image path. However, if there is more than one image path in the array, I need to display an additional select input so they can select the appropiate image.

How could something like this be achieved?

Thanks

Answer

You would need to have an empty < select > ready to be unhidden. Once you have the data you could populate the select like this-

$.each($imageArray, function(key, value) {   
 $('#myEmptyAndNowUnhiddenSelect')
     .append($("<option></option>")
     .attr("value",key)
     .text(value)); 
});