i’m trying to display drop-down menus ‘category’and subcategories. it’s been a few years since I used javascript, so I am having some problems. the code I have simply is not populating the html select input. I don’t know if the code is too simplistic or if I have just made some small error, but I cant seem to get it work. maybe someone can show me where I’m going wrong. Thanks.
<html>
<select name="cat" id="menu1" class="menu"></select>
<select name="subcat" id="menu2" class="menu"></select>
</html>
<script type = "text/javascript">
var data = {
"category":["sub-category"],
"music": ["sub-category","rock", "punk"],
"film": ["sub-categoy","comedy", "drama"],
"tv": ["sub-catery","sit-com", "soap opera"],
}
for (var i in data) {
$('#menu1').append('<option>' + i + '</option>');
}
$('#menu1').change(function() {
var key = $(this).val();
$('#menu2').empty();
for (var i in data[key]) {
$('#menu2').append('<option>' + data[key][i] + '</option>');
}
}).trigger('change');
</script>
You’ve posted jQuery code. E.g.:
$('#menu1')So be sure to call the jQuery library in a script tag, and place all such code inside a jQuery block like this:
UPDATE
I’ve fixed the code to make it work. See it in action here: http://jsfiddle.net/QYcMt/1/