开发者

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 w开发者_开发技巧ant to use select here. I want to use the element's ID so that I can use the same function for multiple elements.)

Thanks.


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


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜