Quote:
quote:Originally posted by ketki
I have 2 drop downs. Both the drop downs are related. In the sense that after choosing some option from one drop down ,the options in the second drop down should change relative to the value chosen in first drop down. options in both dropdowns are coming from the database. I guess i will need to use javascript. I am working on PHP.
BUT sending values from one script to another is a problem.
|
Basically, you have three options.
The new and fashionable one is AJAX; your write an onChange event handler for the first drop-down that sends an asynchronous HTTP request to the database and retrieves the content to put into the second drop-down to match the option selected in the first.
There are two more traditional approaches. One is to reload the script when the first dropdown changes and populate the second one based on the value chosen in the first. Another is to use PHP to dump all data that can be used to populate the second dropdown, but do the actual populating with JavaScript.
Here is a static example of the last approach:
<script language="JavaScript">
function populateSelect2(n) {
switch (n) {
case "1":
document.forms[0].elements[1].options[0] = new Option("Option 1-1", "1");
document.forms[0].elements[1].options[1] = new Option("Option 1-2", "2");
document.forms[0].elements[1].options[2] = new Option("Option 1-3", "3");
document.forms[0].elements[1].options.length = 3;
break;
case "2":
document.forms[0].elements[1].options[0] = new Option("Option 2-1", "1");
document.forms[0].elements[1].options[1] = new Option("Option 2-2", "2");
document.forms[0].elements[1].options[2] = new Option("Option 2-3", "3");
document.forms[0].elements[1].options[3] = new Option("Option 2-4", "4");
document.forms[0].elements[1].options[4] = new Option("Option 2-5", "5");
document.forms[0].elements[1].options.length = 5;
break;
case "3":
document.forms[0].elements[1].options[0] = new Option("Option 3-1", "1");
document.forms[0].elements[1].options[1] = new Option("Option 3-2", "2");
document.forms[0].elements[1].options[2] = new Option("Option 3-3", "3");
document.forms[0].elements[1].options[3] = new Option("Option 3-4", "4");
document.forms[0].elements[1].options.length = 4;
break;
}
}
</script>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="select1" onChange="populateSelect2(select1.value)">
<option value=1>Option 1
<option value=2>Option 2
<option value=3>Option 3
</select>
<select name="select2">
<option value=0>Select more options...
</select>
</form>
The content inside the populateSelect2() function can be generated dynamically by PHP. The advantage of this approach is that changes in the second dropdown are instantaneous. The disadvantage is that in some situations you may have too much data to transfer this way.