Royal Pinto
Royal Pinto

Reputation: 183

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.

Upvotes: 5

Views: 10722

Answers (3)

kazinix
kazinix

Reputation: 30113

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>");

Upvotes: 3

Molecular Man
Molecular Man

Reputation: 22386

$('#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"]');

Upvotes: 8

Raul Agrait
Raul Agrait

Reputation: 6018

Looks like you want to use append. Example:

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

If you want to insert items in between one another, you can use insertBefore or insertAfter:

myOption.insertAfter("$#idOfItemIWantToInsertAfter");

Upvotes: 1

Related Questions