As you can see from my code, I have taken it from another site.
I would like to add a fourth drop down to the page. It needs to the be first drop down. The type drop down.
The code I have only allows 3 dynamic drop downs, it is basically a state, city and country drop down that I have ammended to suit my needs.
I have added it to a jsfiddle
<tr>
<td width="254" style="text-align: left;">
<p>
Type:
<select name="Type" id="Type">
<option value=""></option>
<option value="Monthly">Monthly</option>
<option value="Annually">Annually</option>
</select>
</p>
<tr>
<td width="254" style="text-align: left;">
Box:
<select name="country" id="country" onchange="setStates();">
<option value=""></option>
<option value="Sky HD">Sky HD</option>
<option value="Sky+">Sky+</option>
<option value="Sky Standard">Sky Standard</option>
</select>
</td>
<td width="252" style="text-align: left;">
<p> </p>
</td>
</tr>
<tr>
<td style="text-align: left;">
Product :
<select name="state" id="state" onchange="setCities();">
<option value=""></option>
</select>
</td>
<td style="text-align: left;">
<p> </p>
</td>
</tr>
<tr>
<td style="text-align: left;">
Price :
<select name="city" type="text" id="city" />
</td>
<td style="text-align: left;">
</td>
</tr>
The Javascript code
/* This script and many more are available free online at
The JavaScript Source!! http://www.javascriptsource.com
Created by: Michael J. Damato | http://developing.damato.net/ */
// State lists
var states = new Array();
states['Sky HD'] = new Array('Platinum', 'Gold', 'Diamond');
states['Sky+'] = new Array('Platinum', 'Gold', 'Diamond');
states['Sky Standard'] = new Array('Platinum', 'Gold', 'Diamond');
// City lists
var cities = new Array();
cities['Sky HD'] = new Array();
cities['Sky HD']['Platinum'] = new Array('£8.49');
cities['Sky HD']['Gold'] = new Array('£7.49');
cities['Sky HD']['Diamond'] = new Array('£6.49');
cities['Sky+'] = new Array();
cities['Sky+']['Platinum'] = new Array('£8.49');
cities['Sky+']['Gold'] = new Array('£7.49');
cities['Sky+']['Diamond'] = new Array('£6.49');
cities['Sky Standard'] = new Array();
cities['Sky Standard']['Platinum'] = new Array('£8.49');
cities['Sky Standard']['Gold'] = new Array('£7.49');
cities['Sky Standard']['Diamond'] = new Array('£6.49');
function setStates() {
cntrySel = document.getElementById('country');
stateList = states[cntrySel.value];
changeSelect('state', stateList, stateList);
setCities();
}
function setCities() {
cntrySel = document.getElementById('country');
stateSel = document.getElementById('state');
cityList = cities[cntrySel.value][stateSel.value];
changeSelect('city', cityList, cityList);
}
function changeSelect(fieldID, newOptions, newValues) {
selectField = document.getElementById(fieldID);
selectField.options.length = 0;
for (i=0; i<newOptions.length; i++) {
selectField.options[selectField.length] = new Option(newOptions[i], newValues[i]);
}
}
// Multiple onload function created by: Simon Willison
// http://simonwillison.net/2004/May/26/addLoadEvent/
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(function() {
setStates();
});
The script that this is based on is not ideal if I understand your data model correctly. Besides what is mentioned in comments, the State / City scenario has a hierarchy to it, that does not seem applicable to your use case. The list of products appears to be identical regardless of which box I choose, correct? And the combination yields a unique price?
If so, the script you're starting with differs from your desired result in at least two ways:
There is no point in updating the other dropdowns, when another dropdown changes
You should never be able to select the price at all, so this doesn't need to be a dropdown.
I would begin by defining a readable data source, of all the options and their resulting prices:
var prices = [
{ type: 'monthly', box: 'Sky HD', product: 'Platinum', price: '$ 10' },
{ type: 'monthly', box: 'Sky HD', product: 'Gold', price: '$ 20' },
{ type: 'monthly', box: 'Sky HD', product: 'Diamond', price: '$ 30' },
{ type: 'monthly', box: 'Sky+', product: 'Platinum', price: '$ 40' },
...
];
After that, define the different filters. For each filtered property, I'll assume there exists a select with a corresponding class.
var options = ['type','box','product'];
With that taken care of, iterate over the options, find the unique values for that option in the data source and populate the dropdowns. Also, add an on change listener to each dropdown.
options.forEach(function(opt) {
var drop = document.querySelector('.'+opt);
var unique = Object.keys(prices.reduce(function(x,y) { return x[y[opt]] = 1, x; }, {}));
unique.forEach(function(value) {
var htmlOption = document.createElement('option');
htmlOption.value = htmlOption.innerText = value;
drop.options.add(htmlOption);
});
drop.onchange = function() {
updatePrice();
};
});
All that remains is to define updatePrice, which is called each time any of the dropdowns are changed. We iterate through all properties again, and filter out only the prices that match the current selection. If your data source is set up correctly, that should leave you with exactly one match. You could of course add error handling to this to verify that:
function updatePrice() {
var matches = prices;
options.forEach(function(opt) {
var drop = document.querySelector('.'+opt);
matches = matches.filter(function(price) { return price[opt] == drop.value; });
});
document.querySelector('.price').innerText = matches[0].price;
};
Done. Call updatePrice once to set up the initial value:
updatePrice();
This is assuming your scripts are placed last in body. If they're in head, you need to defer the call to updatePrice, and also the setting up of the dropdowns, until DOMReady.
Fiddle
Update: For IE8 compatibility, convenience functions Array.prototype.forEach has been rewritten as regular for loops; Array.prototype.reduce, Array.prototype.filter and Object.prototype.keys has been replaced with functions that roughly mimics their behavior.
IE8-updated fiddle
Related
I am trying to write a script for changing the hidden input value according to selected options.
I have hindi data stored on a variable and I need to pick this hindi data according to english data selected in select feild. The select options are working fine so far, but I am unable to fectch the related hindi data.
var stateObject = {
"Bihar": {
"Begusarai": ["Bachhwara", "Bakhari", "Balia", "Barauni", "Begusarai", "Bhagwanpur", "Birpur", "Cheriya Bariyarpur", "Chhorahi", "Dandari", "Garhpura", "Khudabandpur", "Mansoorchak", "Matihani", "Nawkothi", "Sahebpur Kamal", "Samho Akha Kurha", "Teghra"],
},
}
var stateObjectHindi = {
"बिहार": {
"बेगूसराय": ["बछवारा", "बखरी", "बलिया", "बरौनी", "बेगुसराय", "भगवानपुर", "बीरपुर", "चेरिया बरियारपुर", "छौराही", "डंडारी", "गढ़पुरा", "खोदाबंदपुर", "मंसूरचक", "मटिहानी", "नावकोठी", "साहेबपुर कमाल", "साम्हो अखा कुरहा", "तेघरा"],
},
}
window.onload = function() {
var stateList = document.getElementById("stateList"),
stateListHindi = document.getElementById("stateListHindi"),
districtList = document.getElementById("districtList"),
districtListHindi = document.getElementById("districtListHindi"),
blockList = document.getElementById("blockList"),
blockListHindi = document.getElementById("blockListHindi");
for (var country in stateObject) {
stateList.options[stateList.options.length] = new Option(country, country);
}
stateList.onchange = function() {
districtList.length = 1; // remove all options bar first
blockList.length = 1; // remove all options bar first
if (this.selectedIndex < 1) return; // done
for (var state in stateObject[this.value]) {
districtList.options[districtList.options.length] = new Option(state, state);
}
}
stateList.onchange(); // reset in case page is reloaded
districtList.onchange = function() {
blockList.length = 1; // remove all options bar first
if (this.selectedIndex < 1) return; // done
var district = stateObject[stateList.value][this.value];
for (var i = 0; i < district.length; i++) {
blockList.options[blockList.options.length] = new Option(district[i], district[i]);
stateListHindi.value = this.value;
}
}
}
<select name="state" id="stateList">
<option value="" selected="selected">Select State</option>
</select>
<select name="district" id="districtList">
<option value="" selected="selected">Select District</option>
</select>
<select name="block" id="blockList">
<option value="" selected="selected">Select Block</option>
</select>
<br/> State in Hindi: <input type="hidden" class="stateListHindi" id="stateListHindi" name="stateListHindi" value="" /><br/> District in Hindi: <input type="hidden" class="districtListHindi" id="districtListHindi" name="districtListHindi" value="" /><br/>Block in Hindi: <input type="hidden" class="blockListHindi" id="blockListHindi" name="blockListHindi" value="" /><br/>
JSFiddle Demo
Your data structure is perhaps not too well-suited for what you want here. You need to find the corresponding property in both objects, for the first two levels, by their position - so you will have to extract the keys first, and use indexOf to locate them.
So for the state first of all, that would be
var selectedKeyIndex = Object.keys(stateObject).indexOf(this.value);
stateListHindi.value = Object.keys(stateObjectHindi)[selectedKeyIndex];
Extract the keys from the English object, and find the index of the property matching the current selection in there. Then use that index, to extract the corresponding property name from the Hindi object.
Now, for the district, you'll have to do the same thing, but for one more level:
var selectedKeyIndex = Object.keys(stateObject[stateList.value]).indexOf(this.value);
districtListHindi.value = Object.keys(stateObjectHindi[stateListHindi.value])[selectedKeyIndex];
And then for the Blocks, which are in an array, you can select directly by index,
var selectedKeyIndex = stateObject[stateList.value][districtList.value].indexOf(this.value);
blockListHindi.value = stateObjectHindi[stateListHindi.value][districtListHindi.value][selectedKeyIndex];
All of it put together here: https://jsfiddle.net/6g5ad4cz/.
(I made the hidden fields into normal text fields, so that the result can be visually checked straight away.)
I am currently new to Vue.js and this is my first question on stack so forgive me if I am not the most clear.
I am trying to create multiple dynamic select filters to filter a list that I have gotten from an api using axios.
I have surfaced the data within my HTML template and have managed to create the two filters, my main issue is that I need the filters to only display unique values (no duplicates) and this is where I am struggling.
This is mainly a proof of concept for work which displays a group of users names, there label and position. We where using angularjs before and are now looking to move over to Vue.js, so I haven't gotten to grips with it yet, and currently stumped as I don't understand how to make the information from one source data array filter another source data array.
Here is what I have currently in my app.js
new Vue({
el: "#vueApp",
data: {
users: [],
JobRole: '',
Label: '',
search: '',
JobRoles: [],
},
created: function() {
this.getResults();
},
methods: {
getResults: function() {
var vm = this;
axios.get("APIData").then(function(response) {
console.log(response.data.value);
vm.users = response.data.value;
})
},
filterPosition:function() {
var vm = this;
vm.item.Position = event.target.value;
},
filterLabel:function() {
var vm = this;
vm.item.Meta.Label = event.target.value;
}
},
computed: {
JobRoleList: function(){
var vm = this;
var JobRoles = [];
vm.users.forEach(function(item){
if(!JobRoles.includes(item.Position)){
JobRoles.push(item.Position);
console.log(JobRoles);
}
});
return JobRoles;
},
filterAll: function(){
var vm = this;
var filtered = vm.users;
// var JobRoles = vm.JobRoles;
if (vm.search) {
filtered = vm.users.filter(function(item){
return item.People.Title.indexOf(vm.search) > -1
});
}
if (vm.Label) {
filtered = filtered.filter(function(item){
return item.Meta.Label.match(vm.Label)
});
}
if (vm.JobRole) {
vm.JobRole = filtered.filter(function(item){
return item.Position.match(vm.JobRole)
console.log(JobRole);
});
}
return filtered
console.log(filtered);
},
}
});
Here is my Markup
<div id="vueApp">
<div>
<select v-model="JobRole">
<option value="">Select a Position</option>
<option v-for="item in JobRoleList" :value="item.Position">{{item}}</option>
</select>
<select v-model="Label">
<option value="">Select a Label</option>
<option v-for="item in filterAll" :value="item.Meta.Label">{{item.Meta.Label}}</option>
</select>
<input type="text" v-model="search" placeholder="Search...">
<table>
<tr>
<th>Name</th>
<th>Department</th>
<th>Position</th>
<!-- <th>People Title</th> -->
</tr>
<tr v-for="item in filterAll">
<td>{{item.People.Title}}</td>
<td>{{item.Meta.Label}}</td>
<td>{{item.Position}}</td>
</tr>
</table>
</div>
</div>
So what I want to get to is have each filter to have unique values with no duplication and to filter the information within the list.
I have managed to create a unique value array for one of the select filters under JobRoleList, I just need to know how to have it communicate with the filterAll array, if I can get to that stage then all I would need to do is replicate that for the other filter.
I would appreciate any help and would be more than happy to provide more detail.
There are a few problems with your code:
You're binding the wrong value to the job role select. Right now your code says :value="item.Position" when the JobRoleList variable is an array of strings. So when you click select there won't be a value for JobRole
<select v-model="JobRole">
<option value="">Select a Position</option>
<option v-for="item in JobRoleList" :value="item.Position">{{item}}</option>
</select>
You're filtering the wrong variable in your filterAll computed variable in the jobRole part
if (vm.JobRole) {
vm.JobRole = filtered.filter(function(item){
return item.Position.match(vm.JobRole)
console.log(JobRole);
});
// This should say "filtered =" not "vm.JobRole ="
}
There's also a much more succinct way to get a unique list of values using ES6:
JobRoleList: function({ users }) {
return [...new Set(users.map(d => d.Position))];
}
You can also make your search all lower case letters before matching to improve the user experience.
filtered = users.filter(function(item){
return item.People.Title.toLowerCase().indexOf(search.toLowerCase()) > -1
});
I've made a codepen with a working demo: https://codepen.io/CodingDeer/pen/abomBXP
I'm using the dropdown list contained in http://www.javascriptsource.com/forms/country-state-city-drop-down-list.html
// State lists
var states = new Array();
states['Canada'] = new Array('Alberta', 'British Columbia', 'Ontario');
states['Mexico'] = new Array('Baja California', 'Chihuahua', 'Jalisco');
states['United States'] = new Array('California', 'Florida', 'New York');
// City lists
var cities = new Array();
cities['Canada'] = new Array();
cities['Canada']['Alberta'] = new Array('Edmonton', 'Calgary');
cities['Canada']['British Columbia'] = new Array('Victoria', 'Vancouver');
cities['Canada']['Ontario'] = new Array('Toronto', 'Hamilton');
cities['Mexico'] = new Array();
cities['Mexico']['Baja California'] = new Array('Tijauna', 'Mexicali');
cities['Mexico']['Chihuahua'] = new Array('Ciudad Juárez', 'Chihuahua');
cities['Mexico']['Jalisco'] = new Array('Guadalajara', 'Chapala');
cities['United States'] = new Array();
cities['United States']['California'] = new Array('Los Angeles', 'San Francisco');
cities['United States']['Florida'] = new Array('Miami', 'Orlando');
cities['United States']['New York'] = new Array('Buffalo', 'new York');
function setStates() {
cntrySel = document.getElementById('country');
stateList = states[cntrySel.value];
changeSelect('state', stateList, stateList);
setCities();
}
function setCities() {
cntrySel = document.getElementById('country');
stateSel = document.getElementById('state');
cityList = cities[cntrySel.value][stateSel.value];
changeSelect('city', cityList, cityList);
}
function changeSelect(fieldID, newOptions, newValues) {
selectField = document.getElementById(fieldID);
selectField.options.length = 0;
for (i = 0; i < newOptions.length; i++) {
selectField.options[selectField.length] = newOption(newOptions[i], newValues[i]);
}
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(function() {
setStates();
});
Head < script type = "text/javascript"
src = "countryStateCity.js" > << / script > Body < fieldset style = "width: 230px;" > <legend><strong>Make your selection</strong></legend> < p > <form name="test" method="POST" action="processingpage.php">
<table>
<tr>
<td style="text-align: left;">Country:</td>
<td style="text-align: left;">
<select name="country" id="country" onchange="setStates();">
<option value="Canada">Canada</option>
<option value="Mexico">Mexico</option>
<option value="United States">United States</option>
</select>
</td>
</tr><tr>
<td style="text-align: left;">State:</td>
<td style="text-align: left;">
<select name="state" id="state" onchange="setCities();">
<option value="">Please select a Country</option>
</select>
</td>
</tr><tr>
<td style="text-align: left;">City:</td>
<td style="text-align: left;">
<select name="city" id="city">
<option value="">Please select a Country</option>
</select>
</td>
</tr>
</table>
</form> < /fieldset>
I have got the code to work OK but only with small content. When I load all countries, states & regions, & cities & towns into countryStateCity.js file my computer runs out of memory.
The "countryStateCity.js" file is huge. If I list all the countries and all the states & regions and the cities & towns of the countries starting with "A" & "B" everything works OK, but if I add the cities & towns of the countries starting with "C" the system fails.
I need to break up the source file into maybe 1 for each country similar to this;
src="country/Canada.js"
src="country/Mexico.js"
src="country/United States.js"
I want Javascript to find a file name like country/Canada.js, rather than find a name within the whole world file.
Can somebody provide me with amended "Javascript" coding?
OK. This is simple to do. I don't have access to your country file so I don't know how it is scoped or broken up, IE arrays or JSON. So my code is just a mash of yours and it will not work. But it shows how you can solve your problem with a fast end result for the user experience.
The trick is just to load the data that is needed when you need it. Usually this is done with an API, you call it via ajax tell it what you want and boom it sends it back so your UI can show it.
In this scenario we don't have a server so we will do it by dynamically loading scripts into the dom. In this case country data filled with states and City's. One file per country when requested.
It would be better to load state data then cities per state and so on. As well as potentially considering if data should be removed from the Dom if memory is an issue:
//
// Some globals to store what the user selects.
//
VAR _COUNTY, _STATE, _CITY;
//
// This will append scripts to the body so that you dont need to load all the
// scripts in one go, this is the trick.
//
function addScript( src,callback) {
var s = document.createElement( 'script' );
s.setAttribute( 'src', src );
s.onload=callback;
document.body.appendChild( s );
}
//
// Get all the states based on country
// add the correct file to the dom
// ie: country/Canada.js
// these files would be better scoped geodata.country geodata.state.
//
// IMPORTANT CHANGE YOUR HTML SELECT HANDLER TO FIRE HERE.
// <select name="country" id="country" onchange="getStates();">
//
function getStates(){
_COUNRTY = document.getElementById('country'),
file = ["country/",_COUNTRY,".js"].join;
addScript(file, setStates);
};
//
//
// Called when the script loads
//
function setStates() {
//
// Here is where we would do
// geodata.states for now I'm using your declaration of state.
//
var stateList = states;
changeSelect('state', stateList, stateList);
// Not sure why you are doing this they need to select a state first?
setCities();
}
//
// Called when they select a state,
// I would replicate the state code and load all the cities per state.
// I would disable the city drop down until the states are loaded.
//
function setCities() {
_STATE = document.getElementById('state');
cityList = cities[_COUNTRY][_STATE];
changeSelect('city', cityList, cityList);
}
function changeSelect(fieldID, newOptions, newValues) {
selectField = document.getElementById(fieldID);
selectField.options.length = 0;
for (i=0; i<newOptions.length; i++) {
selectField.options[selectField.length]=newOption(newOptions[i],newValues[i]);
}
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(function() {
setStates();
});
I have a java / Spring MVC application that includes forms that interface with tables. On one of the pages, I have designed it so that when a row is clicked on the table, form data is populated using the data that is in that row.
Javascript code:
$('#table tbody').on('click', 'tr', function () {
var idx = table.row(this).index();
var vName = document.getElementById("userName");
vName.value = table.cell(idx, 7).data();
This works well for the text form fields. Where I am running into a problem is in the "userName" field, since that is a list (form:select) field.
I'm not really sure how I would go about the process of having my app be able to locate the list index of a name in the dropdown list based on the text data that it is reading from the table.
Here is the html for the dropdown field:
<spring:bind path="model.userName">
<label for="fullName">Select User:</label>
<form:select cssClass="form-control" path="model.userName" id="userName" name="userName">
<form:option value=""></form:option>
<form:options items="${userList}" itemLabel="fullName" itemValue="ID"/>
</form:select>
</spring:bind>
The dropdown list, ${userList}, is created by building a List in my DAO, along with the following RowMapper method:
private static class UserRowMapper implements RowMapper {
public Object mapRow(ResultSet rs, int i) throws SQLException {
return new Users(rs.getLong("ID"),
rs.getString("LNAME") + ", " + rs.getString("FNAME"));
}
}
When you set a value of a select element, in fact you are setting the option with this value as selected, while here you are using the name so you are dealing with the content of the option and not it's value.
So in your example when you have the selected userName from your table you just need to loop through the select options and set the appropriate option as selected.
This is the code you need:
$('#table tbody').on('click', 'tr', function() {
var idx = table.row(this).index();
var vName = document.getElementById("userName");
for (i in vName.options) {
//I test on the innerText here because FF doesn't support it
var optionText = typeof vName.options[i].innerText !== 'undefined' ? vName.options[i].innerText : vName.options[i].textContent;
if (optionText === table.cell(idx, 7).data()) {
vName.selectedIndex = i;
break;
}
}
});
This is a brief Snippet Example:
$('#name').on('change', function() {
var vName = document.getElementById("userName");
for (i in vName.options) {
var optionText = typeof vName.options[i].innerText !== 'undefined' ? vName.options[i].innerText : vName.options[i].textContent;
if (optionText === $(this).val()) {
vName.selectedIndex = i;
break;
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Enter name:
<input type="text" id="name" />
<select name="userName" id="userName">
<option value="">Muhammad</option>
<option value="">Alain</option>
<option value="">John</option>
<option value="">Ali</option>
<option value="">Maria</option>
<option value="">Lee</option>
<option value="">Alessandro</option>
</select>
Usually the best way to get data from a server to the front end is as a JSON string/object then we can easily manipulate that just like you're doing already.
I think you're pretty much there you're just missing one part.
In this below example i'm listing the same users in a table and menu and on click of the table row the selected user in the drop down is defaulted.
For example with this sample table data.
JS:
var users = [{
ID: 0,
LNAME: "First",
FNAME: "Senior"
}, {
ID: 1,
LNAME: "Second",
FNAME: "Sir"
}, {
ID: 2,
LNAME: "Third",
FNAME: "Chap"
}, {
ID: 3,
LNAME: "Fourth",
FNAME: "Mr"
}];
mag.module('userName', {
view: function(state) {
state.tr = state.option = users.map(function(user) {
return {
_selected: user.ID == state.index ? true : null,
_text: user.FNAME + ' ' + user.LNAME,
_value: user.ID
}
});
state.$tr = {
_onclick: function(e, i) {
state.index = i;
state.span = users[i].FNAME + users[i].LNAME
}
}
}
});
HTML:
<div id="userName">
<table>
<tr></tr>
</table>
<hr/>
<label for="fullName">Select User: <span></span></label>
<select class="form-control" name="userName">
<option></option>
</select>
</div>
Here is the full working example: http://jsbin.com/bokiqebezo/1/edit?html,js,output
Hope this helps!
I'm new to JavaScript. my problem is, i have 3 select html tags. one for country, next for State and the last one is for city. i have different tables like countries,states,cities. the problem is when l click the particular country, the corresponding states would be loaded using onchange event in java script.after loading it i need to click the state then the corresponding cities should load.
but i don't know the coding. if any one have it please send me. its urgent. my boss is waiting for my result.
If you just search the internet you would get lots of solutions from which you can choose depending on the server side technology you use. Here is one using ASP.Net and JQuery
http://beyondrelational.com/modules/2/blogs/80/posts/10655/cascading-drop-down-examplecountry-state-and-city-in-jquery.aspx
StackOverflow is not a site where you can get work done from others. You need to put in time and effort and only when you do get stuck without any answers available should you post your questions here. I'm downmarking your question for this reason.
You are going to have to look into AJAX. What you're trying to accomplish is exceedingly common. There are heaps of examples if you do a quick google search for cascading dropdowns.
Since you'll be dealing with AJAX, I suggest you start out with a library such as jQuery, as building for browser compatibility is a time consuming task without it.
To get you started, you would need a basic structure like the following:
$('#my-select').change(function() {
// code that will be evaluated when #my-select changes
});
From there, you would initiate an AJAX request roughly like so:
var country = $('#my-select').val();
$.post('/get-states', { country: country }, function(res) {
// code that will be evaluated when the ajax request completes
});
In the callback above, you would populate the child dropdowns.
If i did understand correctly, what you want to do is AJAX.
when the onchange event happens, the javascript code sends a request to a server's PHP(or any other server scripts) that process the requests, and sends back the data to the javascript that process the data and outputs to the user.
I don't know the code myself from the top of my head, but i can recommend that you look at Jquery and its plugins, there you will surely find the code you want, and quickly assemble the whole process..
EDIT: and i just found your answer thanks to the other answer : Cascade Dropdown List using jQuery/PHP
JS:
var states = new Array();
states['Canada'] = new Array('Alberta','British Columbia','Ontario');
states['Mexico'] = new Array('Baja California','Chihuahua','Jalisco');
states['United States'] = new Array('California','Florida','New York');
// City lists
var cities = new Array();
cities['Canada'] = new Array();
cities['Canada']['Alberta'] = new Array('Edmonton','Calgary');
cities['Canada']['British Columbia'] = new Array('Victoria','Vancouver');
cities['Canada']['Ontario'] = new Array('Toronto','Hamilton');
cities['Mexico'] = new Array();
cities['Mexico']['Baja California'] = new Array('Tijauna','Mexicali');
cities['Mexico']['Chihuahua'] = new Array('Ciudad Juárez','Chihuahua');
cities['Mexico']['Jalisco'] = new Array('Guadalajara','Chapala');
cities['United States'] = new Array();
cities['United States']['California'] = new Array('Los Angeles','San Francisco');
cities['United States']['Florida'] = new Array('Miami','Orlando');
cities['United States']['New York'] = new Array('Buffalo','new York');
function setStates() {
cntrySel = document.getElementById('country');
stateList = states[cntrySel.value];
changeSelect('state', stateList, stateList);
setCities();
}
function setCities() {
cntrySel = document.getElementById('country');
stateSel = document.getElementById('state');
cityList = cities[cntrySel.value][stateSel.value];
changeSelect('city', cityList, cityList);
}
function changeSelect(fieldID, newOptions, newValues) {
selectField = document.getElementById(fieldID);
selectField.options.length = 0;
for (i=0; i<newOptions.length; i++) {
selectField.options[selectField.length] = new Option(newOptions[i], newValues[i]);
}
}
// Multiple onload function created by: Simon Willison
// http://simonwillison.net/2004/May/26/addLoadEvent/
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(function() {
setStates();
});
HTML:
<fieldset style="width: 230px;">
<legend><strong>Make your selection</strong></legend>
<p>
<form name="test" method="POST" action="processingpage.php">
<table>
<tr>
<td style="text-align: left;">Country:</td>
<td style="text-align: left;">
<select name="country" id="country" onchange="setStates();">
<option value="Canada">Canada</option>
<option value="Mexico">Mexico</option>
<option value="United States">United States</option>
</select>
</td>
</tr><tr>
<td style="text-align: left;">State:</td>
<td style="text-align: left;">
<select name="state" id="state" onchange="setCities();">
<option value="">Please select a Country</option>
</select>
</td>
</tr><tr>
<td style="text-align: left;">City:</td>
<td style="text-align: left;">
<select name="city" id="city">
<option value="">Please select a Country</option>
</select>
</td>
</tr>
</table>
</form>
</fieldset>
It took me 5 seconds to google and paste it. Plz do some research before posting.
original source: http://www.javascriptsource.com/forms/country-state-city-drop-down-list.html