Check if value is in select list with JQuery

前端 未结 7 2416
小蘑菇
小蘑菇 2020-12-13 17:06

How can I, using JQuery, check if a value belongs to dropdown list or not?

相关标签:
7条回答
  • 2020-12-13 17:12

    Here is another similar option. In my case, I'm checking values in another box as I build a select list. I kept running into undefined values when I would compare, so I set my check this way:

    if ( $("#select-box option[value='" + thevalue + "']").val() === undefined) { //do stuff }
    

    I've no idea if this approach is more expensive.

    0 讨论(0)
  • 2020-12-13 17:16
    if ($select.find('option[value=' + val + ']').length) {...}
    
    0 讨论(0)
  • 2020-12-13 17:17

    Why not use a filter?

    var thevalue = 'foo';    
    var exists = $('#select-box option').filter(function(){ return $(this).val() == thevalue; }).length;
    

    Loose comparisons work because exists > 0 is true, exists == 0 is false, so you can just use

    if(exists){
        // it is in the dropdown
    }
    

    Or combine it:

    if($('#select-box option').filter(function(){ return $(this).val() == thevalue; }).length){
        // found
    }
    

    Or where each select dropdown has the select-boxes class this will give you a jquery object of the select(s) which contain the value:

    var matched = $('.select-boxes option').filter(function(){ return $(this).val() == thevalue; }).parent();
    
    0 讨论(0)
  • 2020-12-13 17:23

    Use the Attribute Equals Selector

    var thevalue = 'foo';
    var exists = 0 != $('#select-box option[value='+thevalue+']').length;
    

    If the option's value was set via Javascript, that will not work. In this case we can do the following:

    var exists = false;
    $('#select-box option').each(function(){
        if (this.value == 'bar') {
            exists = true;
            return false;
        }
    });
    
    0 讨论(0)
  • 2020-12-13 17:23

    if(!$('#select-box').find("option:contains('" + thevalue  + "')").length){
    //do stuff
    }

    0 讨论(0)
  • 2020-12-13 17:24

    I know this is kind of an old question by this one works better.

    if(!$('.dropdownName[data-dropdown="' + data["item"][i]["name"] + '"] option[value="'+data['item'][i]['id']+'"]')[0]){
      //Doesn't exist, so it isn't a repeat value being added. Go ahead and append.
      $('.dropdownName[data-dropdown="' + data["item"][i]["name"] + '"]').append(option);
    }
    

    As you can see in this example, I am searching by unique tags data-dropdown name and the value of the selected option. Of course you don't need these for these to work but I included them so that others could see you can search multi values, etc.

    0 讨论(0)
提交回复
热议问题