javascript - How to find and remove duplicate entry from dropdown list -
javascript - How to find and remove duplicate entry from dropdown list -
this question has reply here:
filter duplicate options select dropdown 3 answersi have dropdown list having duplicate entries. 1 of duplicate entry selected value in dropdown. eg:
<select id="country"> <option value="nz">new zealand</option> //new zealand selected alternative <option value="usa">united states</option> <option value="ind">india</option> <option value="nz">new zealand</option> <option value="sa">south africa</option> <option value="uk">united kingdom</option> <option value="jp">japan</option> </select>
now, im trying remove new zealand alternative (duplicate), @ same time, im trying create other entry of new zealand selected, see list as:
<select id="country"> <option value="usa">united states</option> <option value="ind">india</option> <option value="nz" selected>new zealand</option> //removing duplicate selection. <option value="sa">south africa</option> <option value="uk">united kingdom</option> <option value="jp">japan</option> </select>
here javascript used populate dropdown:
$.ajax('/url/allcountries', { method:'get', success: function(items){ if(items){ var items = items; $.each(items, function(i, item) { $("#country").append($('<option></option>').val(item.code).html(item.name)); //eg: item.code = "usa" , item.name ="united states" if($("#country :selected").text() === item.code){ $("#country :selected").html(item.name); //edit per suggested var x = {}; $("select[id='country'] > option").each(function () { if(x[this.text]) { $(this).remove(); } else { x[this.text] = this.value; } }); //this gives me duplicate entry @ top of list. } }); } //if status ends }//success ends });
any ideas on how remove duplicates , create of them selected?
you need create array of unique items before .each()
. can done many different ways. here one way it.
javascript jquery
Comments
Post a Comment