Adding an item to a dropdown using jQuery with a specific index

Is it possible?

I use append like this

$(".ddl").append($("<option></option>").val("").text("Select"));

But that adds it to the end.

+5
source share
3 answers

if you want to add as index 2 you can do this:

$(".dll option").eq(2).before($("<option></option>").val("").text("Select"));

this means select index 2 and put a new parameter in front of it.

+11
source

Find the parameter .eq(n)to indicate the index in which you want to include the new parameter. Then use .before()to insert the object. (See Also .insertBefore(), .insertAfter()or .after())

$(".ddl option").eq(n).before($("<option></option>").val("").text("Select")); 
+1
source

dll, var dll = $(".dll")

dll.children("option").eq(2).before($("<option></option>").val("").text("Select"));
0

All Articles