Reputation: 411
I want to change options of my second select depending on what I chose from the first select. Once again, I know where my code should be, I know that I need a if statement, and many if else but I am stuck in php now. If I select "Acura" I want, for example, my $modele_acura shows up in my second select tag.
(Thanks to all of you, many beginner programmers, as myself, should be so thankfully for all of your help guys, thanks in advance!)
<?php
$marques = array(
'Acura',
'Aston Martin',
'Audi',
'Bentley',
'BMW',
'Buick',
'Cadillac',
'Chevrolet',
'Chrysler',
'Dodge',
'Ferrari',
'Fiat',
'Ford',
'GMC',
'Honda',
'Hyundai',
'Infiniti',
'Jaguar',
'Jeep',
'Kia',
'Lamborghini',
'Land Rover',
'Lexus',
'Lincoln',
'Lotus',
'Mazda',
'Mercedes-Benz',
'MINI',
'Mitsubishi',
'Nissan',
'Pontiac',
'Porsche',
'Ram',
'Saab',
'Saturn',
'Scion',
'Smart',
'Subaru',
'Suzuki',
'Toyota',
'Volkswagen',
'Volvo'
);
$modele_acura = array(
'1',
'2',
);
$modele_aston = array(
'3',
'4',
);
?>
<body>
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="post">
<select id="marque" name="marque">
<option></option>
<?php
foreach($marques as $marque => $value)
{
echo '<option value="'.$marque.'">'.$value.' </option>';
}
?>
</select>
<select>
<option></option>
<?php
echo '<option value=""></option>';
// I AM STUCK HERE :(
?>
</select>
</form>
</body>
Upvotes: 3
Views: 454
Reputation: 780974
Change your $modele_XXX
arrays to a single associative array:
$modele = array('acura' => array(1, 2),
'aston' => array(3, 4),
...
);
Change your HTML to:
<body>
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="post">
<select id="marque" name="marque">
<option></option>
<?php
foreach($marques as $marque => $value)
{
echo '<option value="'.$marque.'">'.$value.' </option>';
}
?>
</select>
<select id="modele" name="modele">
</select>
</form>
</body>
And add this jQuery code to your PHP script, sometime after assigning $modele
above.
$(function() {
var modele = <?php echo json_encode($modele); ?>; // Convert PHP array to Javascript
$("#marque").change(function() {
$("#modele").html("<option/>"); // Initial empty value
var selected_modele = $(this).val();
if (selected_modele) {
var modele_vals = modele[selected_modele.toLowerCase()];
$.each(modele_vals, function(i, elem) {
$("#modele").append($("<option/>", { value: elem, text: elem }));
});
}
});
});
Upvotes: 2