Setting the selected attribute on a select list using jQuery

后端 未结 10 940
渐次进展
渐次进展 2020-12-01 00:15

I have the following HTML:


                        
    
提交评论

  • 2020-12-01 00:32

    You can follow the .selectedIndex strategy of danielrmt, but determine the index based on the text within the option tags like this:

    $('#dropdown')[0].selectedIndex = $('#dropdown option').toArray().map(jQuery.text).indexOf('B');
    

    This works on the original HTML without using value attributes.

    0 讨论(0)
  • 2020-12-01 00:37

    If you are using JQuery, since the 1.6 you have to use the .prop() method :

    $('select option:nth(1)').prop("selected","selected");
    
    0 讨论(0)
  • 2020-12-01 00:38

    I'd iterate through the options, comparing the text to what I want to be selected, then set the selected attribute on that option. Once you find the correct one, terminate the iteration (unless you have a multiselect).

     $('#dropdown').find('option').each( function() {
          var $this = $(this);
          if ($this.text() == 'B') {
             $this.attr('selected','selected');
             return false;
          }
     });
    
    0 讨论(0)
  • 提交回复
    热议问题