Reputation: 9093
In my current spring project, I have some <select>
fields where the options inside are added through this jquery code:
function load_options(target, lista) {
$.ajax({
type: 'GET',
url: lista
}).done(function(data){
var json = jQuery.parseJSON( data );
$.each(json.item, function(index, item) {
var option = $('<option class="form-control" value="'+item.id+'">'+item.nome+'</option>');
if(<<condition>>)
target.append(option);
});
});
}
I am looking for a <<condition>>
where I can verifiy if the option stored in the variable exists before add it to select.
Anyone know how check this?
Upvotes: 1
Views: 53
Reputation: 138
The jQuery constructor (that's where you pass in your selector) returns an array, so, if an element exists the length property of that array is 1 (or more). You could write you condition based on that.
Upvotes: 1
Reputation: 35680
I would do it this way, but I'd be interested in other solutions:
...
var json = jQuery.parseJSON( data );
var opt = [];
...
if(!opt[item.nome])
target.append(option);
opt[item.nome]= true;
...
Upvotes: 1