How can I check whether a option already exist in select by JQuery

后端 未结 8 840
余生分开走
余生分开走 2020-11-30 19:22

How can I check whether a option already exist in select by JQuery?

I want to dynamically add options into select and so I need to check whether the option is alread

相关标签:
8条回答
  • 2020-11-30 19:59

    It's help me :

      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");
                             }
      });
    
    0 讨论(0)
  • 2020-11-30 20:01
    if ( $("#your_select_id option[value=<enter_value_here>]").length == 0 ){
      alert("option doesn't exist!");
    }
    
    0 讨论(0)
  • 2020-11-30 20:05

    This evaluates to true if it already exists:

    $("#yourSelect option[value='yourValue']").length > 0;
    
    0 讨论(0)
  • 2020-11-30 20:07
    var exists = $("#yourSelect option")
                   .filter(function (i, o) { return o.value === yourValue; })
                   .length > 0;
    

    This has the advantage of automatically escaping the value for you, which makes random quotes in the text much easier to deal with.

    0 讨论(0)
  • 2020-11-30 20:07

    Does not work, you have to do this:

    if ( $("#your_select_id option[value='enter_value_here']").length == 0 ){
      alert("option doesn't exist!");
    }
    
    0 讨论(0)
  • 2020-11-30 20:07

    I had a similar issue. Rather than run the search through the dom every time though the loop for the select control I saved the jquery select element in a variable and did this:

    function isValueInSelect($select, data_value){
        return $($select).children('option').map(function(index, opt){
            return opt.value;
        }).get().includes(data_value);
    }
    
    0 讨论(0)
提交回复
热议问题