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

前端 未结 11 1468
野的像风
野的像风 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:00

    try this:

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

    In case someone google for this, the solutions above didn't work for me so i ended using "pure" javascript

    document.getElementById("The id of the element").value = "The value"
    

    And that would set the value and make the current value selected in the combo box. Tested in firefox.

    it was easier than keep googling a solution for jQuery

    0 讨论(0)
  • 2020-12-04 18:06

    I tried a few of these things until I got one to work in both Firefox and IE. This is what I came up with.

    $("#my-Select").val($("#my-Select" + " option").filter(function() { return this.text == myText }).val());
    

    another way of writing it in a more readable fasion:

    var valofText = $("#my-Select" + " option").filter(function() {
        return this.text == myText
    }).val();
    $(ElementID).val(valofText);
    

    Pseudocode:

    $("#my-Select").val( getValOfText( myText ) );
    
    0 讨论(0)
  • 2020-12-04 18:08

    When an <option> isn't given a value="", the text becomes its value, so you can just use .val() on the <select> to set by value, like this:

    var text1 = 'Monkey';
    $("#mySelect1").val(text1);
    
    var text2 = 'Mushroom pie';
    $("#mySelect2").val(text2);
    

    You can test it out here, if the example is not what you're after and they actually have a value, use the <option> element's .text property to .filter(), like this:

    var text1 = 'Monkey';
    $("#mySelect1 option").filter(function() {
        return this.text == text1; 
    }).attr('selected', true);
    
    var text2 = 'Mushroom pie';
    $("#mySelect2 option").filter(function() {
        return this.text == text2; 
    }).attr('selected', true);​
    

    You can test that version here.

    0 讨论(0)
  • 2020-12-04 18:10

    I usually use:

    $("#my-Select option[text='" + myText +"']").attr("selected","selected") ;
    
    0 讨论(0)
  • 2020-12-04 18:13

    If you want to selected value on drop-down text bases so you should use below changes: Here below is example and country name is dynamic:

        <select id="selectcountry">
        <option value="1">India</option>
        <option value="2">Ireland</option>
        </select>
        <script>
         var country_name ='India'
         $('#selectcountry').find('option:contains("' + country_name + '")').attr('selected', 'selected');
        </script>
    
    0 讨论(0)
提交回复
热议问题