I am trying to dynamically populat the drop down list based on the selected value of first list.
NOTE: Both dropdowns are multiple selection dropdown:
This is the code for my dropdowns:
<select id="dis" name="dis[]" onChange="AjaxFunction();" class="form-control selectpicker show-menu-arrow" multiple title="Select a City or Division">
// my discrictes goes here
</select>
<select id="zone" name="zone[]" class="form-control show-menu-arrow" multiple title="Choose Educational Zone" ></select>
To do this I found AjaxFunction() javascript function. And its as below:
function AjaxFunction(){
var httpxml;
try {
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateck() {
if(httpxml.readyState==4) {
var myarray = JSON.parse(httpxml.responseText);
// Before adding new we must remove previously loaded elements
for(j=document.getElementById('s2').length-1;j>=0;j--) {
document.getElementById('s2').remove(j);
}
for (i=0;i<myarray.data.length;i++) {
var optn = document.createElement("OPTION");
optn.text = myarray.data[i].name_si;
optn.value = myarray.data[i].zone_id;
document.getElementById('s2').options.add(optn);
}
}
}
var str='';
var s1ar=document.getElementById('s1');
for (i=0;i< s1ar.length;i++) {
if(s1ar[i].selected) {
str += s1ar[i].value + ',';
}
}
//alert (s1ar);
var str=str.slice(0,str.length -1); // remove the last coma from string
//alert(str);
//alert(str);
var url="../includes/dropdown-zones.php";
url=url+"?dis_id="+str;
url=url+"&sid="+Math.random();
//alert(url);
httpxml.onreadystatechange=stateck;
httpxml.open("GET",url,true);
//httpxml.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
httpxml.setHeader('Content-type', 'application/json');
httpxml.send(null);
}
My question is, now I need to convert above function to jquery, because I am looking for a jQuery/Ajax solution for this:
This is how I tried it using jQuery:
$('#dis').on('change',function() {
var str='';
var s1ar=document.getElementById('dis');
for (i=0;i< s1ar.length;i++) {
if(s1ar[i].selected) {
str += s1ar[i].value + ',';
}
}
var str=str.slice(0,str.length -1);
var url="../includes/dropdown-zones.php";
url=url+"?dis_id="+str;
url=url+"&sid="+Math.random();
$.ajax({
type: "GET",
url: url,
contentType: "application/json; charset-utf-8",
dataType: "json",
success: function(data) {
$('#zone').empty();
$('#zone').append("<option value=''>- Select Zone-</option>");
$.each(data, function(i,item){
var selecting;
if (selected === data[i].id) {
selecting = ' selected="selected"';
} else {
selecting = '';
}
$('#zone').append('<option '+selecting+' value="'+data[i].id+'">'+data[i].name+'</optoin>');
});
},
complete: function() {}
});
});
But is not working for me. Can anybody help me out to figure this out?
Thank you
