javascript - Dynamic dropdown without external file -
i have been trying achieve dynamic dropdown list on page. idea when user changes 1 drop down next 1 populates based on first one.
i have been using tutorial here: https://css-tricks.com/dynamic-dropdowns/ guide using external text/json files. understand how modify code either text/json not need use external files (i.e. can have options within html file)
for text code looks like:
$("#first-choice").change(function() { $("#second-choice").load("textdata/" + $(this).val() + ".txt"); });
for json code looks like:
$("#first-choice").change(function() { var $dropdown = $(this); $.getjson("jsondata/data.json", function(data) { var key = $dropdown.val(); var vals = []; switch(key) { case 'beverages': vals = data.beverages.split(","); break; case 'snacks': vals = data.snacks.split(","); break; case 'base': vals = ['please choose above']; } var $secondchoice = $("#second-choice"); $secondchoice.empty(); $.each(vals, function(index, value) { $secondchoice.append("<option>" + value + "</option>"); }); }); });
thanks
a simple solution have multiple hidden drop downs, displayed dependant on value of first:
$('.first').change(function(){ $('.option').removeclass('show'); var val = $(this).val(); switch(val){ case 'option 1': $('.option.one').addclass('show'); break; case 'option 2': $('.option.two').addclass('show'); break; case 'option 3': $('.option.three').addclass('show'); break; } })
.option{ display:none; } .show{ display:block; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select class="first"> <option>option 1</option> <option>option 2</option> <option>option 3</option> </select> <select class="option 1 show"> <option>a</option> <option>b</option> <option>c</option> </select> <select class="option two"> <option>d</option> <option>e</option> <option>f</option> </select> <select class="option three"> <option>g</option> <option>h</option> <option>i</option> </select>
or in jquery manually set arrays
$("#first-choice").change(function() { var $dropdown = $(this); var key = $dropdown.val(); var vals = [] var beverages = ["tea" , "coffee" , "juice"]; var snacks = ["burger" , "sandwich" , toast"]; switch(key) { case 'beverages': vals = beverages; break; case 'snacks': vals = snacks; break; case 'base': vals = ['please choose above']; } var $secondchoice = $("#second-choice"); $secondchoice.empty(); $.each(vals, function(index, value) { $secondchoice.append("<option>" + value + "</option>"); }); });
Comments
Post a Comment