Friday, 15 May 2015

javascript - Hiding the currently selected option -



javascript - Hiding the currently selected option -

i surrently having issue using jquery. have 2 select fields.

<select id="cat" name="cat_id"> <option value="2">cat 2</option> <option value="3">cat 3</option> <option value="4">cat 4</option> </select> <select id="subcat" name="subcat_id"> <option class="subcats cat_2" value="1">subcat 1</option> <option class="subcats cat_2" value="2">subcat 2</option> <option class="subcats cat_3" value="3">subcat 3</option> <option class="subcats cat_3" value="4">subcat 4</option> <option class="subcats cat_3" value="5">subcat 5</option> <option class="subcats cat_0" value="0">no subcats cat</option> </select>

and here javascript code

<script type="text/javascript"> var curval = $("#cat").val(); $(".subcats").hide(0); $(".cat_"+curval).show(0); $("#cat").change(function(){ var cat = $(this).val(); $(".subcats").removeattr("selected").hide(0); if($(".cat_"+cat).length == 0){$(".cat_0").show(0);} else{$(".cat_"+cat).show(0);} }); </script>

here problem. when alter value of cats select, options subcats changed correctly. however, selected field still showing (even if doesn't correspond current cat).

any help appreciated.

you should alter code little bit on hange event can add together selected attribute first element in available options :)

class="snippet-code-js lang-js prettyprint-override">var curval = $("#cat").val(); $(".subcats").hide(0); $(".cat_" + curval).show(0); $("#cat").change(function() { var cat = $(this).val(); $(".subcats").removeattr("selected").hide(0); if ($(".cat_" + cat).length == 0) { $(".cat_0").attr("selected", "selected").show(0); } else { $(".cat_" + cat).eq(0).attr("selected", "selected"); $(".cat_" + cat).show(0); } }); class="snippet-code-html lang-html prettyprint-override"><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <select id="cat" name="cat_id"> <option value="2">cat 2</option> <option value="3">cat 3</option> <option value="4">cat 4</option> </select> <select id="subcat" name="subcat_id"> <option class="subcats cat_2" value="1">subcat 1</option> <option class="subcats cat_2" value="2">subcat 2</option> <option class="subcats cat_3" value="3">subcat 3</option> <option class="subcats cat_3" value="4">subcat 4</option> <option class="subcats cat_3" value="5">subcat 5</option> <option class="subcats cat_0" value="0">no subcats cat</option> </select>

javascript jquery

No comments:

Post a Comment