默认情况下,组合框选择最后一个选项

时间:2012-06-18 11:00:40

标签: jquery html html5

我想要一个组合框默认选择最后一个选项(使用jquery):

<select>
    <option>item1</option>
    <option>item2</option>
    <option>item3</option>
    <option>item4</option>
    <option>item5</option>
</select>

5 个答案:

答案 0 :(得分:32)

做这样的事情:

$(function() {
    $("select option:last").attr("selected", "selected");
});

答案 1 :(得分:9)

一个简单的JavaScript解决方案:

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

Demo

答案 2 :(得分:2)

<select>
    <option>item1</option>
    <option>item2</option>
    <option>item3</option>
    <option>item4</option>
    <option selected="selected">item5</option>
</select>

答案 3 :(得分:1)

使用&#34; prop&#34;而不是&#34; attr&#34;当然取决于您使用的jQuery版本。

$(&#34; select option:last&#34;)。prop(&#34; selected&#34;,&#34; selected&#34;);

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

关于何时使用prop或attr的更多讨论: .prop() vs .attr()

答案 4 :(得分:0)

只需使用原始Javascript,就可以结合dom对象的 .selectedIndex .length 属性来实现以下目的:

document.querySelector("#mySelect").selectedIndex = document.querySelector("#mySelect").length - 1;
<select id="mySelect">
    <option>item1</option>
    <option>item2</option>
    <option>item3</option>
    <option>item4</option>
    <option>item5</option>
</select>