How can I insert a <option> into a <select> mutiple element using jQuery?

How can I insert <option>into a <select>(multiple) element using jQuery?

(I don't want to use select here. I want to use the element identifier so that I can use the same function for multiple elements.)

Thank.

+5
source share
3 answers
$('#elementsID').append('<option>my new option</option>');

UPDATE

to insert after an option that is similar to <option value="value1">option with value1</option>:

var newOption = $('<option value="newOpt">my new option</option>');
newOption.insertAfter('#elementsID option[value="value1"]');
+8
source

In add option:

$('#colors').append('<option>red</option>');

In set the parameter before or after another parameter:

$('<option>blue</option>').insertBefore("#colors option:contains('red')");
$('<option>yellow</option>').insertAfter("#colors option:contains('blue')");

:

$("#colors option:contains('blue')").replaceWith("<option>pink</option>");

:

$('#colors')
   .html("<option>green</option>" +
         "<option>orange</option>" +
         "<option>violet</option>");
+3

It looks like you want to use append . Example:

var myOption = $("<option value='Option X'>X</option>");
$("#selectId").append(myOption);

If you want to insert elements into each other, you can use insertBefore or insertAfter :

myOption.insertAfter("$#idOfItemIWantToInsertAfter");
+1
source

All Articles