Reputation: 1619
So I need to create two dropdown lists where second list is dependent on the first one. For example:
In first list I may have options like this:
When users selects A, then he will get to chose additional options in second dropdown based on the first dropdown. So In case user chose A in first list, options in second list may be:
How can I do this in php and html ? Do I have to use multidimensional arrays ? Maybe database ? How would I detect what user has selected in first list and offer him proper options in second ?
Upvotes: 1
Views: 4448
Reputation: 14004
With HTML and PHP only you could do this with a multidimensional array like this:
<?php
$list = array(
"A" => array("A-1", "A-2", "A-3"),
"B" => array("B-1", "B-2"),
"C" => array("C-1"),
"D" => array("D-1", "D-2", "D-3", "D-4"),
);
?>
<form>
<select name="first_input">
<?php foreach ($list as $first => $second) { ?>
<option><?php print ($first); ?></option>
<?php } ?>
</select>
<input type="submit">
</form>
<?php if (isset($_GET["first_input"])) { ?>
<form>
<select name="second_input">
<?php foreach ($list[$_GET["first_input"]] as $second) { ?>
<option><?php print ($second); ?></option>
<?php } ?>
</select>
</form>
<?php } ?>
Upvotes: 1
Reputation: 3363
I did one the other day using a multidimensional array.
var options = {
"Option 1" : [ "1A","1B","1C" ],
"Option 2" : [ "2A","2B","2C" ],
"Option 3" : [ "3A","3B","3C" ]
}
Then something like:
$.each(options,function(a,b){
$('#select1').append('<option>'+a+'</option>');
});
$('#select1').change(function(){
var sel1 = $(this).val();
$.each(option[$sel1],function(a,b) {
$('#select2').append('<option>'+b+'</option>');
});
});
(This is the concept... this actual syntax may or may not be error-ridden.)
Upvotes: 0