Dipak
Dipak

Reputation: 357

How to insert option at specified index of select(Multiple) in html?

How can I insert an option element at a specified index in a <select multiple> element?

Thanks

Upvotes: 33

Views: 29225

Answers (6)

Supriyo Saha
Supriyo Saha

Reputation: 11

This should work. Replace ELEMENT_NAME with the id of your Single/Multi Select and INDEX_VALUE with the specified index, and VALUE with your string data.

Syntax:

document.getElementById("ELEMENT_NAME").options[INDEX_VALUE].innerHTML = "VALUE";

Example:

document.getElementById("MyOption").options[0].innerHTML = "HTMLisNotAProgrammingL";

Upvotes: 0

Carl Sharman
Carl Sharman

Reputation: 4845

Vanilla javascript (no jQuery) and cross browser.

To insert a new option into the select "mySelect", with value of "1" and text of "text", before the 0th existing item:

mySelect.options.add(new Option("text", "1"), mySelect.options[0]);

See: https://developer.mozilla.org/en/docs/Web/API/HTMLSelectElement#add%28%29

Upvotes: 16

pizzamonster
pizzamonster

Reputation: 1266

I submit this answer because jquery was not specified in the question.

function insertOptionToSelect(select, idx, option) {
    var saved = [];
    var i;
    for (i = 0; i < select.options.length; i++) {
        saved.push(select.options[i]);
    }
    select.options.length = 0;
    for (i = 0; i < idx; i++) {
        select.options[select.options.length] = saved[i];
    }
    select.options[select.options.length] = option;
    while (i < saved.length) {
        select.options[select.options.length] = saved[i++];
    }
}

The following will insert an option at the selected index of select with id 'MyPizzaSelect':

var myselect = document.getElementById('MyPizzaSelect');
insertOptionToSelect(myselect, myselect.selectedIndex, new Option('Pizza Margarita', '12345'));

Upvotes: 3

Brian
Brian

Reputation: 2778

And yet another option, sans jquery:

Markup:

<select multiple="multiple" id="mySelect">
    <option>First</option>
    <option>Third</option>
</select>

JS:

<script type="text/javascript">
    var myDdl = document.getElementById("mySelect");
    var myOption = document.createElement("OPTION");
    myOption.innerText = "Second";

    myDdl.options.insertBefore(myOption, myDdl.options[myDdl.options.length - 1]);

</script>

Upvotes: 4

Joseph Marikle
Joseph Marikle

Reputation: 78530

Here's a way you can do it:

var myOption = "<option>Dynamic Option</option>";
var index = 2;
$(myOption).insertBefore("select option:nth-child("+index+")");

fiddle example

Upvotes: 2

Corneliu
Corneliu

Reputation: 2942

$("select option").eq(index).before($("<option></option>").val(val).html(text));

Upvotes: 25

Related Questions