I am trying to avoid a duplicate here, as did not see my issue resolved in any of the the other ‘jQuery Select Menu’ posts around SO. Just looking to be nudged in the right direction.
I have a set of select boxes for searching through the results of cars by make and model. Naturally, The first <select> is for the Make of a car. This <select> element is being populated on page load with PHP. Once a Make is selected a makeID is passed through AJAX to retrieve the set of models relative to the selected Make.
This is all working great, my problem is that when I make multiple selections to my Make list, it never refreshes the second <select> box, thus appending models to many different makes to the second <select> box.
How can I refresh the second <select> box to only show the current results relative to the selection of the first <select> box.
My HTML:
<form method="post" action="">
<p>
<label for="make">Make</label>
<select name="make" id="make">
<?php foreach ($usedMakes->MakeResult as $MakeResult) { ?>
<option value="<?php echo $MakeResult->makeId; ?>"><?php echo $MakeResult->makeName; ?></option>
<?php } ?>
</select>
</p>
<p>
<label for="model">Model</label>
<select name="model" id="model">
<option value="" selected>Make a Selection</option>
</select>
</p>
<p>
<button name="submit" id="submit"> Submit </button>
</p>
</form>
My JavaScript:
$("#make").change(function() {
var makeId = $(this).val();
$.ajax({
url: "process.inc.php?makeId=" + makeId,
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
for(i = 0 ; i < data.length; i++) {
var modelId = data[i].ModelResult.modelId;
var modelName = data[i].ModelResult.modelName;
var response = "<option value=\"" + modelId + "\">" + modelName + "</option>";
var appendedData = $(response).insertAfter($("#model option:first-child"));
$("#model option:first-child").data(appendedData);
};
}
});
});
Remove the options
You should only update the once you build the whole list, not in a for loop