jQuery: Setting select list 'selected' based on text, failing strangely

前端 未结 11 1469
野的像风
野的像风 2020-12-04 17:31

I have been using the following code (with jQuery v1.4.2) to set the \'selected\' attribute of a select list based on its \'text\' description rather than its \'value\':

相关标签:
11条回答
  • 2020-12-04 18:14

    Using the filter() function seems to work in your test cases (tested in Firefox). The selector would look like this:

    $('#mySelect1 option').filter(function () {
        return $(this).text() === 'Banana';
    });
    
    0 讨论(0)
  • 2020-12-04 18:14
    setSelectedByText:function(eID,text) {
        var ele=document.getElementById(eID);
        for(var ii=0; ii<ele.length; ii++)
            if(ele.options[ii].text==text) { //Found!
                ele.options[ii].selected=true;
                return true;
            }
        return false;
    },
    
    0 讨论(0)
  • 2020-12-04 18:21

    The following works for text entries both with and without spaces:

    $("#mySelect1").find("option[text=" + text1 + "]").attr("selected", true);
    
    0 讨论(0)
  • 2020-12-04 18:22

    We can do it by searching the text in options of dropdown list and then by setting selected attribute to true.

    This code is run in every environment.

     $("#numbers option:contains(" + inputText + ")").attr('selected', 'selected');
    
    0 讨论(0)
  • 2020-12-04 18:26
    $("#my-select option:contains(" + myText +")").attr("selected", true);
    

    This returns the first option containing your text description.

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