I have a two drop down menus in a form, and I want the options in the second drop down to change based on the selection in the first. Eventually I will also add a 3rd select based on the 2nd, and a 4th based on the 3rd.
I stored the options in an array and have written a long if statement to pull in the corresponding array based on the first selection, but seems like there has to be a better way to do this rather than repeating all the code. This does the job but I would like to improve the code.
I have looked at tutorials online which refer to databases and JSON data, and I can't quite wrap my head around it. I do have access to a database on a different server/domain than this form will live on but am not very familiar with databases so this was an easier path for me to go down. There are a few posts I've seen on this site too but they're very specific (like mine) and don't help me.
Hope this makes sense. This is my first time using arrays or trying to do anything like this so thanks in advance for helping me learn!
JSfiddle: http://jsfiddle.net/QhBLq/
Here is my code:
$(document).ready(function() {
$('div' + '.menu').hide();
$('a').click(function ()
{
$('#' + $(this).attr('class')).show().siblings('div').hide();
});
var cookwareProds = [ "Round French Oven", "Oval French Oven", "Braiser", "Skillet", "Fry Pan", "Grill Pan", "Saute Pan", "Saucepan", "Saucier", "Griddle", "Roaster", "Stockpot", "Speciality Cookware", "Other"];
var bakewareProds = [ "Covered Casserole", "Baking Dish", "Stoneware Gratin", "Speciality Bakeware", "Individual Bakeware", "Metal Bakeware", "Other"];
var kitchenToolProds = [ "Utensils", "Kitchen Accessories", "Cutlery", "Wine Tools", "Textiles", "Other"];
var dineEntertainProds = [ "Dinnerware", "Serveware", "Tabletop Accessories", "Glassware", "Kettles", "Tea Collection", "Café Collection", "Other"];
var prodSelect = $('select');
prodSelect.change(function () {
var catSelected = $(this).val();
$('#subCats').fadeIn('fast');
$(this).parent("li").next().find("select > option").remove(); /*Prevents previous options from persisting in menu if parent category selection is changed*/
if (catSelected == 'Cookware') {
$.each(cookwareProds, function(key, value) {
$('#product-type')
.append($("<option></option>")
.attr("value",value)
.text(value));
});
}
if (catSelected == 'Bakeware') {
$.each(bakewareProds, function(key, value) {
$('#product-type')
.append($("<option></option>")
.attr("value",value)
.text(value));
});
}
if (catSelected == 'Kitchen Tools') {
$.each(kitchenToolProds, function(key, value) {
$('#product-type')
.append($("<option></option>")
.attr("value",value)
.text(value));
});
}
if (catSelected == 'Dine & Entertain') {
$.each(dineEntertainProds, function(key, value) {
$('#product-type')
.append($("<option></option>")
.attr("value",value)
.text(value));
});
}
if (catSelected == 'Other') {
$(this).next('.other').show();
} else $(this).next('.other').hide();
});
});