jQuery - setting the selected value of a select control via its text description

前端 未结 22 1011
夕颜
夕颜 2020-11-22 09:16

I have a select control, and in a javascript variable I have a text string.

Using jQuery I want to set the selected element of the select control to be the item with

相关标签:
22条回答
  • 2020-11-22 09:36

    I found that by using attr you would end up with multiple options selected when you didn't want to - solution is to use prop:

    $("#myDropDown option:text=" + myText +"").prop("selected", "selected");

    0 讨论(0)
  • 2020-11-22 09:36
     $('#theYear').on('change', function () {
     FY = $(this).find('option:selected').text();
     $('#theFolders').each(function () {
         $('option:not(:contains(' + FY + '))', this).hide();
     });
     $('#theFolders').val(0);
    });
    
    $('#theYear').on('mousedown', function () {
     $('#theFolders option').show().find('option:contains("Select")', this).attr('selected', 'selected');
    });
    
    0 讨论(0)
  • 2020-11-22 09:38

    Easiest way with 1.7+ is:

    $("#myDropDown option:text=" + myText +"").attr("selected", "selected"); 
    

    1.9+

    $("#myDropDown option:text=" + myText +"").prop("selected", "selected"); 
    

    Tested and works.

    0 讨论(0)
  • 2020-11-22 09:38

    Try

    [...mySelect.options].forEach(o=> o.selected = o.text == 'Text C' )
    

    [...mySelect.options].forEach(o=> o.selected = o.text == 'Text C' );
    <select id="mySelect">
      <option value="A">Text A</option>
      <option value="B">Text B</option>
      <option value="C">Text C</option>
    </select>

    0 讨论(0)
  • 2020-11-22 09:41

    I do it on this way (jQuery 1.9.1)

    $("#my-select").val("Dutch").change();
    

    Note: don't forget the change(), I had to search to long because of that :)

    0 讨论(0)
  • 2020-11-22 09:41

    I know this is an old post, but I couldn't get it to select by text using jQuery 1.10.3 and the solutions above. I ended up using the following code (variation of spoulson's solution):

          var textToSelect = "Hello World";
    
          $("#myDropDown option").each(function (a, b) {
                if ($(this).html() == textToSelect ) $(this).attr("selected", "selected");
            });
    

    Hope it helps someone.

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