Réponses:
Cela prend la valeur true s'il existe déjà:
$("#yourSelect option[value='yourValue']").length > 0;
Une autre façon d'utiliser jQuery:
var exists = false;
$('#yourSelect option').each(function(){
if (this.value == yourValue) {
exists = true;
}
});
.length
pourrait le faire.
Cela m'aide:
var key = 'Hallo';
if ( $("#chosen_b option[value='"+key+"']").length == 0 ){
alert("option not exist!");
$('#chosen_b').append("<option value='"+key+"'>"+key+"</option>");
$('#chosen_b').val(key);
$('#chosen_b').trigger("chosen:updated");
}
});
J'ai eu un problème similaire. Plutôt que d'exécuter la recherche dans le dom à chaque fois dans la boucle du contrôle select, j'ai enregistré l'élément jquery select dans une variable et j'ai fait ceci:
function isValueInSelect($select, data_value){
return $($select).children('option').map(function(index, opt){
return opt.value;
}).get().includes(data_value);
}