I have a cascading dropdown with jQuery which is using PHP to retrieve its values. I am trying to nail it so that it works in all situations. Basically it should do the following:
- Populate child when parent is selected
- Parent is sticky so if the page is refreshed child should again auto
populate based on the parent value in the $_POST array. - If possible I would also like child to be sticky so that the
child would also be selected and not just re-populated when the page
is reloaded.
Here is what I have so far:
$("#parent_id").change(function() {
$("#child_id").html("<option value=\"\">-- Select One --</option>");
var p_id = $(this).val();
if(p_id != 0) {
$.getJSON('./php/includes/child_web_service.php?p_id=' + p_id,function(data) {
$.each(data, function() {
$("#child_id").append($("<option></option>").val(this['child_id_key']).html(this['child_name']));
});
});
}
});
<?php
if(isset($_POST['parent_id']) && $_POST['parent_id'] != ""){
echo "$(\"#parent_id\").val(" . $_POST['parent_id'] . ").trigger('change');";
}
?>
Any suggestions on making this more robust would be appreciated.
Thanks
Here are a few suggestions:
$_POSTin a variable to make the parent sticky, and use a ctype to validate it