Ad

Drop-Down Lists With Conditional Data JS

I have a website and I want to include 2 drop down boxes. The values in the second drop down box depend on the first.

For instance if option A in drop down 1 is chosen then the available choices in dropdown box 2 would be 1,2,3

And if option 2 is chosen then drop down box 2 will show 5,6,7.

I've tried using JavaScript to receive the result of the first box as an argument and then use an 'if statement' to select what array of answers should be used by drop box 2 however this has been to no avail

''' I don't have any reasonable code to show '''

From what I've tried I can receive the index of the first drop down box choice however I cannot get the second box to show my array for that choice

Ad

Answer

<html>
<body>
<script type="text/javascript" src="jquery.min.js"></script>
<select id="ddl1">
<option selected value="1">A</option>
<option value="2">B</option>
</select>
<select id="ddl2">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</body>

<script>
$("#ddl1").change(function(){
$('#ddl2 option').remove();
if($("#ddl1 option:selected").val()==1){
    $('#ddl2').append('<option value="1">1</option>');
    $('#ddl2').append('<option value="2">2</option>');
    $('#ddl2').append('<option value="3">3</option>');
    }
else if($("#ddl1 option:selected").val()==2){
    $('#ddl2').append('<option value="5">5</option>');
    $('#ddl2').append('<option value="6">6</option>');
    $('#ddl2').append('<option value="7">7</option>');
    }
});
</script>
</html>
Ad
source: stackoverflow.com
Ad