Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a new option before the last option of a select?

Tags:

jquery

add

option

I'm trying to create a new option on the fly and then add it right before the last option of a select.

When I use $("#select").append("<option>hi</option"), it always adds after the last one.

How do I add a new option before the last option of a select?

like image 267
Moon Avatar asked Jun 28 '11 00:06

Moon


2 Answers

$("select option:last").before("<option>hi</option>");

Online demo: http://jsfiddle.net/6MVEd/

like image 60
amosrivera Avatar answered Oct 13 '22 00:10

amosrivera


$("#select option").eq(-2).after("<option>hi</option")

or

$("#select option").eq(-1).before("<option>hi</option")

"#select option" is a fully valid querySelectorAll selector.

like image 31
user113716 Avatar answered Oct 12 '22 23:10

user113716