Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

Thanks.

like image 834
Royal Pinto Avatar asked Aug 03 '11 05:08

Royal Pinto


2 Answers

$('#elementsID').append('<option>my new option</option>');

UPDATE

to insert after option that lolks like <option value="value1">option with value1</option> use:

var newOption = $('<option value="newOpt">my new option</option>');
newOption.insertAfter('#elementsID option[value="value1"]');
like image 90
Molecular Man Avatar answered Nov 01 '22 15:11

Molecular Man


To append an option:

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

To insert an option before or after another option:

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

To replace an option with another option:

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

To replace all options:

$('#colors')
   .html("<option>green</option>" +
         "<option>orange</option>" +
         "<option>violet</option>");
like image 3
dpp Avatar answered Nov 01 '22 14:11

dpp