Sunday, July 15, 2012

Add Dropdown Country & State List Dynamically into HTML form by Javascript

In this post, we are going to see how to implement the dynamic dropdown with selected values.
<html>
<head>
<script lang="javascript">
var arr = new Array();
arr[0] = new Array("-Select District-");
arr[1] = new Array("Anantapur", "Chittoor", "Kadapa", "Kurnool");
arr[2] = new Array("Bellary", "Bangalore", "Mysore", "Udipi");
arr[3] = new Array("Madras", "Salem", "Coimbuttur");
function stateChange(State) {
var stateValue = State.value;
document.forms["myForm"].elements["District"].options.length = 0;
for (var i = 0; i < arr[stateValue].length; i++) {
var option = document.createElement("option");
option.setAttribute('value', i + 1);
option.innerHTML = arr[stateValue][i];
document.forms["myForm"].elements["District"].appendChild(option);
}
}
</script>
</head>
<body>
<h2>State and District Demo</h2>
<form name="myForm" method="post">
<select name="State" onchange="stateChange(this);">
<option value="0">-Select State-</option>
<option value="1">Andhra Pradesh</option>
<option value="2">Karnataka</option>
<option value="3">Tamil Nadu</option>
</select><br /> <select name="District">
</select>
<center>
<h1>Designed by Ranga Reddy.
</center>
</form>
</body>
</html>
Output:

0 comments: