texto obtener con como change jquery

obtener - ¿Cómo puedo verificar si ya existe una opción en select by JQuery?



select text jquery (6)

Esto se evalúa como verdadero si ya existe:

$("#yourSelect option[value=''yourValue'']").length > 0;

¿Cómo puedo verificar si ya existe una opción en JQuery?

Quiero agregar dinámicamente opciones en select, por lo que debo verificar si la opción ya existe para evitar la duplicación.


Me ayuda:

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"); } });


No funciona, tienes que hacer esto:

if ( $("#your_select_id option[value=''enter_value_here'']").length == 0 ){ alert("option doesn''t exist!"); }


Otra forma de usar jQuery:

var exists = false; $(''#yourSelect option'').each(function(){ if (this.value == yourValue) { exists = true; } });


if ( $("#your_select_id option[value=<enter_value_here>]").length == 0 ){ alert("option doesn''t exist!"); }


var exists = $("#yourSelect option") .filter(function (i, o) { return o.value === yourValue; }) .length > 0;

Esto tiene la ventaja de escaparse automáticamente del valor para usted, lo que hace que las citas aleatorias en el texto sean mucho más fáciles de tratar.