Reputation: 559
I have the following code select box div:
Make:<br>
<select name="Make">
<option value = "Toyota">Toyota</option>
<option value = "Honda">Honda</option>
</select>
<div id="side_model">
Model:<br>
<select name="Model">
<PHP CODE THAT SEARCHES DATABASE FOR ALL MODELS AVAILABLE AND LIST THEM AS OPTIONS ?>
</select>
</div>
And the following Jquery:
<script>
jQuery(document).ready(function($){
$('#Make').change(function() {
$.get('dropdown.php',{make: $(this).val() },function(d){
$('#side_model').html(d);
});
});
});
</script>
This is a very simplified version of my code but what Im doing is, once the make is chosen I query the database in dropwdown php and get all models of that make and then simply populate the list
My dropdown.php looks something like this:
Model:<br>
<select name="Model">
<PHP CODE THAT SEARCHES DATABASE FOR ALL MODELS THAT MATCH THE MAKE SELLECTED AND LIST THEM AS OPTIONS ?>
</select>
Ok so the code pretty much works the way its intended too except for one detail.
Instead of the jQuery replacing the div with the contentes of dropdown.php it is just adding that extra select box on top of it.
How do I get the jQuery code to replace the model select box with the dynamicaly genereated content?
Upvotes: 0
Views: 1462
Reputation: 1753
Maybe clear the div before you refill it?
$('#side_model').empty();
and fill it again with
$('#side_model').append(/*your generated html code*/);
--EDIT--
I also noticed you call $('#make'), but your select only has a name like that, so please add id="make"to your select
Upvotes: 0
Reputation: 7040
It may make more sense to use jQuery's .replaceWith()
function (documentation here):
First, add an ID to your select element
<div id="side_model">
Model:<br>
<select id="Model" name="Model">
<option value='0'>----</option>
</select>
</div>
Then replace it with the return value from the $.get()
:
jQuery(document).ready(function($){
$('#Make').change(function() {
$.get('dropdown.php',{make: $(this).val() },function(d){
$('#Model').replaceWith(d);
});
});
});
Now all you need to do in the background is to generate the select
in its entirety (including the open/close <select>
tags).
UPDATE
I just noticed you're calling $("#Make").change()
but you never give any of your elements an ID set to "Make". Add the ID attribute to your select where name="Make"
:
Make:<br>
<select id="Make" name="Make">
<option value = "Toyota">Toyota</option>
<option value = "Honda">Honda</option>
</select>
Upvotes: 2
Reputation: 1753
I also noticed you call $('#make')
, but your select only has a name like that, so please add id="make"
to your select
Upvotes: 1