skip to Main Content

Problem : I am trying to populate the 1st SELECT on load. And 2nd SELECT depends on the 1st one.
1st select : populated with states
2nd select : should be populated with districts based on selected states.
jSON file is HERE
Solutions given on other stackoverflow documents didn’t meet my requirements

$(document).ready(function(){
  $.ajax({
    type:'GET',
    header:{' Access-Control-Allow-Origin ':'*'},
    datatype:'json',
    url:'https://github.com/sab99r/Indian-States-And-Districts/blob/master/states-and-districts.json'
  })
  .done(function(response){
    console.log(response);
  })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Demo</title>
  </head>
  <body>
    <div class="">
      <select class="states" >
      </select>
      <select class="districts" >
      </select>
    </div>
    <link rel="text/script" href="jquery-3.5.1.js">
    <link rel="text/>script" href="index.js">
  </body>
</html>

3

Answers


  1. Chosen as BEST ANSWER

    I have got a even short code to do it.
    We can use ajax GET to get data from the raw of any repository.
    Solution to the above question :

    $.get('https://raw.githubusercontent.com/aps08/web-development/main/web-dev-series/JSON/indian-states-and-cities.json',  // url
            function (data1, textStatus, jqXHR) {  // success callback
              var data1 = JSON.parse(data1);
              load(data1);
          });
    

    Remember that if u loading data from your local machine then you need to remove
    var data1 =JSON.parse(data1) line


  2. Just set code according to your requirement but you need to set all logic. You need to set when you send state data then you will get all districts

    function changeselect(){
    $.ajax({
        type:'GET',
        header:{' Access-Control-Allow-Origin ':'*'},
        datatype:'json',
        url:'https://github.com/sab99r/Indian-States-And-Districts/blob/master/states-and-districts.json'
      })
      .done(function(response){
        console.log(response);
        response.foreach(function(data){
        $("#distr").append("<option>+data+</option>")
        })
      })
    }
    $(document).ready(function(){
      $.ajax({
        type:'GET',
        header:{' Access-Control-Allow-Origin ':'*'},
        datatype:'json',
        url:'https://github.com/sab99r/Indian-States-And-Districts/blob/master/states-and-districts.json'
      })
      .done(function(response){
        console.log(response);
        response.foreach(function(data){
        $("#distr").append("<option>+data+</option>")
        })
      })
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <!DOCTYPE html>
    <html lang="en" dir="ltr">
      <head>
        <meta charset="utf-8">
        <title>Demo</title>
      </head>
      <body>
        <div class="">
          <select class="states" onchange="changeselect()">
          <option>A</option>      
          <option>B</option>      
          <option>C</option>
    
    
          </select>
          <select class="districts" id="distr">
          </select>
        </div>
        <link rel="text/script" href="jquery-3.5.1.js">
        <link rel="text/>script" href="index.js">
      </body>
    </html>
    Login or Signup to reply.
  3. Below example show an example how to load data, first and then store it in
    a var to prevent ajax loading every change, then in every change fetch data array to load districts :

    ( uring raw url load text , so you have to pare json from string at first )

    See wokring snippet :

    data = [];
    
    $(document).ready(function() {
    
      $(".states").on("change", stateChange);
    
      $.ajax({
          type: 'GET',
          header: {
            ' Access-Control-Allow-Origin ': '*'
          },
          datatype: 'json',
          url: 'https://raw.githubusercontent.com/sab99r/Indian-States-And-Districts/master/states-and-districts.json'
        })
        .done(function(response) {
          var resp = JSON.parse(response);
          loadStates(resp);
        })
    
    });
    
    
    var loadStates = function(response) {
    
      if (response.states) {
        data = response.states;
    
        response.states.forEach(state => {
    
          var option = $('<option/>');
          option.attr({
            'value': state.state,
          }).text(state.state);
          $('.states').append(option);
        })
      }
    }
    
    var stateChange = function(event) {
      let stateValue = event.target.value;
      let state = data.find(state => state.state === stateValue);
      
      $('.districts').html("");
    
      if (state) {
    
        state.districts.forEach(ditrict => {
          var option = $('<option/>');
          option.attr({
            'value': ditrict,
          }).text(ditrict);
          $('.districts').append(option);
        })
    
      }
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    state :
    <select class="states">
    </select>
    <br> distric
    <select class="districts">
    </select>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search