开发者

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

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

When开发者_如何学Python 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?


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

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


$("#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.


I believe you want the .insertBefore() method.


http://jsfiddle.net/

$("#select option:last").prev().append("<option>New Option</option>");

You may want to avoid using select as an id.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜