Check if an select option exists based on text in jQuery 1.7

后端 未结 4 1944
自闭症患者
自闭症患者 2021-02-09 14:26

So I have the following piece of HTML:


                        
    
提交评论

  • 2021-02-09 15:01

    The jQuery filter function accepts a function as its argument:

    $('#sel option').filter(function() { 
        return $(this).text() === "Option1"; 
    });
    
    0 讨论(0)
  • 2021-02-09 15:02
    var length = $('#sel option').filter(function() { 
        return $(this).text() === "Option1"; 
    }).length;
    
    if(length == 0)
        console.log('This option text doesn't exist.');
    else
        console.log('This option text exists ' + length + ' times.');
    

    If length is 0, it doesn't exist. I typically don't like using contains, because it's not an exact match.

    0 讨论(0)
  • 2021-02-09 15:03
    var hasOption1=$("option:contains('Option1')", "#sel").length==1; //true or false
    
    0 讨论(0)
  • 提交回复
    热议问题