Combo Box by default selected the last option

后端 未结 5 1033
忘了有多久
忘了有多久 2021-01-04 02:16

I want a combobox by default selected the last option (using jquery):


                        
    
提交评论

  • 2021-01-04 02:53
    <select>
        <option>item1</option>
        <option>item2</option>
        <option>item3</option>
        <option>item4</option>
        <option selected="selected">item5</option>
    </select>
    
    0 讨论(0)
  • 2021-01-04 02:55

    Do something like this:

    $(function() {
        $("select option:last").attr("selected", "selected");
    });
    
    0 讨论(0)
  • 2021-01-04 03:01

    A plain JavaScript solution:

    select.selectedIndex = select.options.length-1;
    

    Demo

    0 讨论(0)
  • 2021-01-04 03:03

    Use "prop" instead of "attr", of course depending of what version of jQuery you are using.

    $("select option:last").prop("selected", "selected");

    jQuery prop: http://api.jquery.com/prop/

    More discussion on the subject of when to use prop or attr: .prop() vs .attr()

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