Chained select boxes with jquery/php/database not working
It seems that most chained selects are accomplished with JSON, but
unfortunately it's much more convenient for me to use my database to
accomplish this. It's almost there, but for some reason the second select
box is not loading up properly. Instead it's loading the entire HTML for
the page that it's on and I'm not sure why.
Here's what I've got (note that make_list() and model_list() are functions
I previously built that return an array appropriate to their respective
criteria)
The JS:
$(document).ready(function(){
$("select#type").attr("disabled","disabled");
$("select#category").change(function(){
$("select#type").attr("disabled","disabled");
$("select#type").html("<option>loading...</option>");
var id = $("select#category option:selected").attr('value');
$.post("select_type.php", {id:id}, function(data){
$("select#type").removeAttr("disabled");
$("select#type").html(data);
});
});
$("form#select_form").submit(function(){
var cat = $("select#category option:selected").attr('value');
var type = $("select#type option:selected").attr('value');
if(cat>0 && type>0)
{
var result = $("select#type option:selected").html();
$("#result").html('your choice: '+result);
}
else
{
$("#result").html("you must choose two options!");
}
return false;
});
});
The HTML/PHP:
<form>
<div class="clearfix">
<select id="category">
<option value="">Any</option>
<?php foreach ( make_list() as $make ) { ?>
<option value="<?php echo $make ?>"><?php echo $make ?></option>
<?php } ?>
</select>
</div>
<div class="clearfix">
<select id="type">
<option value="">Any</option>
</select>
</div>
</form>
When the first select is changed JQuery should look at a file in the same
folder called 'select_type.php'. Here's what's in that file (strangely
$_POST['id'] doesn't seem to be appending to this file either, despite it
being created in the JS):
foreach ( model_list($_POST['id']) as $model ) {
echo '<option value="'.$model.'">'.$model.'</option>';
}
I've been using this resource for this project:
http://www.yourinspirationweb.com/en/how-to-create-chained-select-with-php-and-jquery/
and it's gotten me most of the way, but unfortunately the data doesn't
seem to be loading into that second select box.
Thanks for looking!
No comments:
Post a Comment