Javascript/jQuery: ensuring unique option added to pulldown -
i have html pulldown menu along text element allows users add new options menu. i'd make sure every option added unique. following 2 lines first option thought of worked (option value = innhtml of options). i'm wondering if there's more elegant solution -- second line seems clunky. doesn't handle spaces in new_name string.
var new_name = document.getelementbyid("preset_name").value var unique_name = $("option[value="+new_name+"]").length === 0 ? true : false
do need this?
html:
<select id="myselect"> <option value="volvo">volvo</option> <option value="saab">saab</option> <option value="mercedes">mercedes</option> <option value="audi">audi</option> </select> <input id="newoption" type="text" /> <button id="check">check</button>
jquery:
$(document).ready(function() { $("button#check").click(function() { var newopt = $("input#newoption").val(); $("#myselect option").each(function(){ var text = $(this).val(); if(newopt.length>0 && text.indexof(newopt)!=-1){ console.log("already present!"); } }); }); });
Comments
Post a Comment