Reputation: 133
I'm working on creating a drop down list that uses a name for the options (different cars). I would like to add a second dropdown list that uses the id from the first drop down list to create a drop down list of different models of each car.
I would like to just use PHP if possible and I believe it is. Here is my code for the first drop down.
function get_vehicle() {
global $db;
$query = $db->prepare("SELECT idmanufacturer, name FROM manufacturer");
$query->execute();
$vehicles = $query->fetchAll();
if(isset($vehicles)) {
echo "<label>Vehicle:</label>";
echo "<select name='vehicle'>";
foreach ($vehicles as $vehicle){
echo '<option value="'.$vehicle['name'].'">'.$vehicle['name'].'</option>';
}echo "</select>";
echo "<br />";
}
}
Upvotes: 1
Views: 1289
Reputation: 289
For this you need to create an ajax function.On change of first dropdown pass its value to the ajax request to any other page and by its id find all car models and display it on second dropdown. Here is an example:- //File name First.php
function get_vehicle() {
global $db;
$query = $db->prepare("SELECT idmanufacturer, name FROM manufacturer");
$query->execute();
$vehicles = $query->fetchAll();
if(isset($vehicles)) {
echo "<label>Vehicle:</label>";
echo "<select name='vehicle' onselect="call_models(this)">";
foreach ($vehicles as $vehicle){
echo '<option value="'.$vehicle['id'].'">'.$vehicle['name'].'</option>';
}echo "</select>";
echo "<br />";
}
}
// this will print first select box
get_vehicle() ;
/* this is second dropdown by default it will be disabled
<select name="cardmodels" id="models" disabled>
<option></option>
</select>
/************* Add ajax function ************/
<script type="text/javascript">
/*********** This function will get the value of first dropdown and will pass the value to the second.php where we will create function to retrieve all models of selected class after fetching this we will return all options of second class. After fetching this we will assign to the second dropdown.
***************/
function call_models(cnt)
{
var model= $(cnt).val();
if(models) {
$.ajax({
type: "POST",
url: "Second.php",
data: {model:model_car}
})
.done(function(responce) {
if(responce!="Not_found") {
$('#models').removeAttr( "disabled" );
$('#models').html(responce);
}
});
}
}
</script>
/************** Second .php *********/ //File name First.php
function get_models($id) {
global $db;
$query = $db->prepare("SELECT model_name FROM car_models where car_id ='".$id."' ");
$query->execute();
$models= $query->fetchAll();
if($models) {
foreach ($models as $model){
echo '<option value="'.$model['name'].'">'.$model['name'].'</option>';
}
}
}
if($_POST) {
get_models($_POST['model']);
} else {
echo "Not_found";
}
?>
Upvotes: 2