16

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

<select>
    <option>item1</option>
    <option>item2</option>
    <option>item3</option>
    <option>item4</option>
    <option>item5</option>
</select>
Bunlong
  • 652
  • 1
  • 9
  • 21

5 Answers5

39

Do something like this:

$(function() {
    $("select option:last").attr("selected", "selected");
});
joan16v
  • 5,055
  • 4
  • 49
  • 49
14

A plain JavaScript solution:

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

Demo

Oriol
  • 274,082
  • 63
  • 437
  • 513
2
<select>
    <option>item1</option>
    <option>item2</option>
    <option>item3</option>
    <option>item4</option>
    <option selected="selected">item5</option>
</select>
U.P
  • 7,357
  • 7
  • 39
  • 61
2

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()

Community
  • 1
  • 1
2

Just using vanilla Javascript you can combine .selectedIndex and .length properties of the < select > dom object in order to achieve this:

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>
Juanma Menendez
  • 17,253
  • 7
  • 59
  • 56