Now using ClassName, but the code repetition does not work.
The first one works, but the second one does not.
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<form name="myform" id="myForm">
<div class="form-row">
<div class="form-group col-md-1">
<select name="optone" class="selectDD form-control stateSel" size="1">
<option value="" selected="selected">Select state</option>
</select>
</div>
<div class="form-group col-md-1">
<select name="opttwo" class="selectDD form-control countySel" size="1">
<option value="" selected="selected">Please select state first</option>
</select>
</div>
<div class="form-group col-md-1">
<select name="optthree" class="selectDD form-control citySel" size="1">
<option value="" selected="selected">Please select county first</option>
</select>
</div>
<br><br><br><br>
<div class="form-group col-md-2">
<select name="optone" class="selectDD form-control stateSel" size="1">
<option value="" selected="selected">Select state</option>
</select> </div>
<div class="form-group col-md-1">
<select name="opttwo" class="selectDD form-control countySel" size="1">
<option value="" selected="selected">Please select state first</option>
</select>
</div>
<div class="form-group col-md-1">
<select name="optthree" class="selectDD form-control citySel" size="1">
<option value="" selected="selected">Please select county first</option>
</select>
</div>
</div>
</form>
<script>
var stateObject = {
"India": {
"Mumbai": ["Bandra", "Goregaon", "Marin Lines"],
"Pune": ["Lal Mahal", "Hinjawadi"],
"Delhi": ["Gurugram", "Karol Bagh"]
},
"United States": {
"California": ["San Diego", "Sears Point"],
"Nevada": ["Las Vegas", "Lamoille Canyon"]
},
"United Kingdom": {
"England": ["Cambridge.", "London", "Bristol"],
"Scotland": ["Glasgow", "Edinburgh"]
}
}
window.onload = function () {
var stateSel = document.getElementsByClassName("stateSel")[0],
countySel = document.getElementsByClassName("countySel")[0],
citySel = document.getElementsByClassName("citySel")[0];
for (var state in stateObject) {
stateSel.options[stateSel.options.length] = new Option(state, state);
}
stateSel.onchange = function () {
countySel.length = 1;
citySel.length = 1;
if (this.selectedIndes < 1) return;
for (var county in stateObject[this.value]) {
countySel.options[countySel.options.length] = new Option(county, county);
}
}
stateSel.onchange();
countySel.onchange = function () {
citySel.length = 1;
if (this.selectedIndex < 1) return;
var cities = stateObject[stateSel.value][this.value];
for (var i = 0; i < cities.length; i++) {
citySel.options[citySel.options.length] = new Option(cities[i], cities[i]);
}
}
}
</script>
</body>
</html>