jquery - Error in my javascript for hiding select options -


i have 2 attribute selections , content of second 1 dependent on selection of first. if select adult, want title option display. if select child, want mr or miss display. wrote simple javascript hide options not needed , works correctly. if select child unwanted options don't show. if change adult, options show. but, if select adult first, dropdown breaks apart , leaves me list of option values.

the javascript used is

$("#attrib-1").change(function () { var id = $(this).find("option:selected").attr("value"); switch (id) {     case "3":         $("#attrib-2 option[value='6']").wrap('<span/>');         $("#attrib-2 option[value='7']").wrap('<span/>');         $("#attrib-2 option[value='9']").wrap('<span/>');         $("#attrib-2 option[value='10']").wrap('<span/>');         break; }  switch (id) {     case "2":         $("#attrib-2 option[value='6']").unwrap();         $("#attrib-2 option[value='7']").unwrap();         $("#attrib-2 option[value='9']").unwrap();         $("#attrib-2 option[value='10']").unwrap();         break; }  }); 

a fiddle can found here. http://jsfiddle.net/2t7oj91d/ can prevent happening if adult first selection?

option elements cannot wrapped in other select. unwrapping them you're forcing renderer remove them select, why html seems break. note hiding/showing option elements not supported across browsers.

with in mind better served enabling/disabling options. add class option elements available adult option , disable/enable them required. try this:

$("#attrib-1").change(function () {     var id = $(this).val();     $("#attrib-2 option.adult").prop('disabled', id == 3); }); 
<select name="id[2]" id="attrib-2">     <option value="4">please select</option>     <option value="5">mr</option>     <option class="adult" value="6">mrs</option>     <option class="adult" value="7">ms</option>     <option value="8">miss</option>     <option class="adult" value="9">dr</option>     <option class="adult" value="10">prof</option> </select> 

updated fiddle


Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -