JSFiddle - React, Tailwind, and code Playground
HTML
<body>
<div align="center">
<h1>Free JavaScript Country/State Selection Demo</h1>
<hr/>
<br/>Select Country (with states):
<select id="country" name="country"></select>
<br />State:
<select name="state" id="state"></select>
<br />district
<select name="district" id="district"></select>
<br/>
<br />
<script language="javascript">
populateCountries("country", "state","district");
</script>
<br/>
<br/>
<br />
<br />
</div>
</body>
JavaScript
// Countries
var country_arr = new Array( "India");
// States
var s_a = new Array();
s_a[0] = "";
s_a[1] = "Tamil Nadu";
s_a[2] = "Tamil Nadu";
function populateStates(countryElementId,districtElement ) {
var selectedCountryIndex = document.getElementById(countryElementId).selectedIndex;
var stateElement = document.getElementById(districtElement);
stateEledistrictElementment.length = 0; // Fixed by Julian Woods
districtElement.options[0] = new Option('Select district ', '');
districtElement.selectedIndex = 0;
var district = s_a[selectedCountryIndex].split("|");
for (var i = 0; i < district .length; i++) {
stateElement.options[districtElement.length] = new Option(district [i], district [i]);
}
}
function populateStates(countryElementId, stateElementId) {
var selectedCountryIndex = document.getElementById(countryElementId).selectedIndex;
var stateElement = document.getElementById(stateElementId);
stateElement.length = 0; // Fixed by Julian Woods
stateElement.options[0] = new Option('Select State', '');
stateElement.selectedIndex = 0;
var state_arr = s_a[selectedCountryIndex].split("|");
for (var i = 0; i < state_arr.length; i++) {
stateElement.options[stateElement.length] = new Option(state_arr[i], state_arr[i]);
}
}
function populateCountries(countryElementId, stateElementId) {
// given the id of the <select> tag as function argument, it inserts <option> tags
var countryElement = document.getElementById(countryElementId);
countryElement.length = 0;
countryElement.options[0] = new Option('Select Country', '-1');
countryElement.selectedIndex = 0;
for (var i = 0; i < country_arr.length; i++) {
countryElement.options[countryElement.length] = new Option(country_arr[i], country_arr[i]);
}
// Assigned all countries. Now assign event listener for the states.
if (stateElementId) {
countryElement.onchange = function () {
...