Setting the selected attribute on a select list using jQuery

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

I have the following HTML:


                        
    
提交评论

  • 2020-12-01 00:21

    If you don't mind modifying your HTML a little to include the value attribute of the options, you can significantly reduce the code necessary to do this:

    <option>B</option>
    

    to

    <option value="B">B</option>
    

    This will be helpful when you want to do something like:

    <option value="IL">Illinois</option>
    

    With that, the follow jQuery will make the change:

    $("select option[value='B']").attr("selected","selected");
    

    If you decide not to include the use of the value attribute, you will be required to cycle through each option, and manually check its value:

    $("select option").each(function(){
      if ($(this).text() == "B")
        $(this).attr("selected","selected");
    });
    
    0 讨论(0)
  • 2020-12-01 00:23

    You can use pure DOM. See http://www.w3schools.com/htmldom/prop_select_selectedindex.asp

    document.getElementById('dropdown').selectedIndex = 1;
    

    but jQuery can help:

    $('#dropdown').selectedIndex = 1;
    
    0 讨论(0)
  • 2020-12-01 00:24

    Something along the lines of...

    $('select option:nth(1)').attr("selected","selected"); 
    
    0 讨论(0)
  • 2020-12-01 00:27
    <select id="cars">
    <option value='volvo'>volvo</option>
    <option value='bmw'>bmw</option>
    <option value='fiat'>fiat</option>
    </select>
    
    var make = "fiat";
    
    $("#cars option[value='" + make + "']").attr("selected","selected");
    
    0 讨论(0)
  • 2020-12-01 00:27

    This can be a solution

    $(document).on('change', 'select', function () {
                var value = $(this).val();
                $(this).find('option[value="' + value + '"]').attr("selected", "selected");
            })
    
    0 讨论(0)
  • 提交回复
    热议问题