How to insert option at specified index of select(Multiple) in html?
How can I insert an option element at a specified ind开发者_如何学编程ex in a <select multiple>
element?
Thanks
$("select option").eq(index).before($("<option></option>").val(val).html(text));
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
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>
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'));
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
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";
精彩评论