0

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

1 Answer 1

1

The code is fine, I am getting error with "selected" is undefined

You can see if(selected === data[i].id) here "selected" variable is not assigned to selected value from first dropdown.

also you need to remove onChange="AjaxFunction();" from first dropdown because now your are using jQuery

Check below code:

$(document).ready(function(){

	$('#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="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 ($('#dis').val().findIndex(x => x==data[i].id)>=0) {
			  selecting = ' selected="selected"'; 
			} else {
			  selecting = '';
			}
			$('#zone').append('<option '+selecting+' value="'+data[i].id+'">'+data[i].name+'</optoin>');
		  });
		}, 
		complete: function() {}
	  }); 
	});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id="dis" class="form-control selectpicker show-menu-arrow" multiple  title="Select a City or Division">
  <option value="1">A</option>
  <option value="2">B</option>
  <option value="3">C</option>
</select>

<select id="zone" class="form-control  show-menu-arrow" multiple  title="Choose Educational Zone" ></select>

The result is some like this:

jSon file value is :

[{
        "id": 1,
        "name": "New"
    },
    {
        "id": 2,
        "name": "Open"
    },
    {
        "id": 3,
        "name": "Close"
    }
]
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your help. But it dosen't populating second dropdown. That is my main problem
Make sure "dropdown-zones.php" is returning value. I have tested this code working, also update above answer with screenshot and json file result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.