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
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 :
Remember that if u loading data from your local machine then you need to remove
var data1 =JSON.parse(data1) line
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
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 :