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
  • 642
  • 1
  • 9
  • 21

5 Answers5

39

Do something like this:

$(function() {
    $("select option:last").attr("selected", "selected");
});
joan16v
  • 4,863
  • 2
  • 47
  • 48
13

A plain JavaScript solution:

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

Demo

Oriol
  • 249,902
  • 55
  • 405
  • 483
2
<select>
    <option>item1</option>
    <option>item2</option>
    <option>item3</option>
    <option>item4</option>
    <option selected="selected">item5</option>
</select>
U.P
  • 7,274
  • 6
  • 36
  • 60
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
  • 12,842
  • 6
  • 48
  • 46