AJAX pre-populated drop down menu
This is a bit complicated so bear with me:
On FORM.php, I have 2 drop down menus:
Plant type
drop down that allows the user to select 'Plant type'.
Plant sub-type
drop down that via AJAX and a call to the database presents multiple choices for 'Plant sub-type'.
AJAX code:
<script type="text/javascript">
function getXMLHTTP() {
var xmlhttp = false;
try {
xmlhttp = new XMLHttpRequest();
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e1) {
xmlhttp = false;
}
}
}
return xmlhttp;
}
function getPlantSubtype(strURL) {
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function () {
if (req.readyState == 4) {
if (req.status == 200) {
document.getElementById('plant_subtype_div').innerHTML = req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
That works perfectly and when I submit, val开发者_开发问答ues are saved in the DB and shown on a table below the form.
Now the user wants to edit this entry, clicking on 'Edit' adjacent to the table cell with the info.
Values for 'Plant type' and 'Plant sub-type' are passed via $_POST
to EDIT.php.
EDIT.php code (using Smarty tags):
<select name="plant_type" onchange="getPlantSubtype('plant_subtype.php?plant_type='+this.value)">
<option selected="selected" value="{$plant_type}">
{$plant_type}
</option>
<option value="" disabled="disabled">
---
</option>
<option value="1">
Tomato
</option>
<option value="2">
Carrot
</option>
</select>
<div id="plant_subtype_div">
<select name="plant_subtype">
<option selected="selected" value="{$plant_subtype}">
{$plant_subtype}
</option>
<option value="" disabled="disabled">
---
</option>
</select>
</div>
On EDIT.php both drop down menus show the correct values.
But when I click on Plant sub-type
drop down the multiple choices are not available.
That's because the form was already pre-populated with $_POST
and onChange
hasn't happened yet.
How do I make Plant sub-type
drop down show its choices when EDIT.php is loaded?
One option is just to call getPlantSubtype('plant_subtype.php?plant_type={$plant_type}')
on the page load.
For example (on the bottom of the page):
<script type="text/javascript">
getPlantSubtype('plant_subtype.php?plant_type={$plant_type}')
</script>
A Better option would be to fetch the subtypes from the same place plant_subtype.php
fetches them from (cache, db) and populate the option values.
精彩评论