[jQuery] How to add unique options to select?
Hi,
I have a form with a select element that contains province names.
If I click a text, an Ajax call rertieves an XML string with all
present provinces in the database.I loop over the nodes in the XML and
append them to the <select> element. That works. Only, when I click a
second time, all the provinces get appended to the select so I end up
with duplicate items.
So I want to check: if the <select> does _not_ contain an <option>
element with the value I currently look at (in the XML node) add it,
else don't.
This is my code:
$("#updateProvinces").click(function(){
$.get(
"http://lab.local/login.cfc",
{method:"getProvinces"},
function(xml){
var select = $("form[name='cityform'] select[name='province']");
$(xml).find('province').each(function(){
if($(select +"/option[@id!="+$(this).attr('id')+"]")){
select.append("<option value="+$(this).attr('id')+">"+$
(this).attr('name')+"</option>");
}
})
}
)
})
Below is the part of the form with the select and update element:
<form name="cityform" method="post">
<table>
<tr>
<td>Provincie:</td>
<td>
<select name="province">
</select> <p id="updateProvinces">update
</td>
</tr>
This does not work, it gets appended anyway. I guess
if($(select +"/option[@id!="+$(this).attr('id')+"]")){
is not correct. Does anyone know how conditionally append an item to
te select element?
Thanks