Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add/remove items to/from an HTML select list using jQuery [closed]

Could somebody recommend some of the best strategies they've used to populate items in an HTML select list on the client side?

I'm using an ASP.NET MVC application and making use of jQuery.

The select list in question is simply a collection of strings which will need to be saved with the model.

I'd rather not have a server call for every item added and simply have everything posted once the form is saved.

Are there any plugins available that can make this easier? Would it be best to write my own pop-up form?

like image 577
David Neale Avatar asked Jul 23 '26 07:07

David Neale


1 Answers

If you need to do a lot of manipulation and support older IE versions where <select> is a bit flaky, yes there is a plugin: jQuery - Select box manipulation plugin, thought it may be overkill for what you're doing.

The alternative is just using selectors for what's needed, for example:

function addItem(val, text) {
  $("#mySelect").append($("<option>", { value: val, text: text }));
}
function removeItem(val) {
  $("#mySelect option[value='"+val+"']").remove();
  //or:
  $("#mySelect option").filter(function(){ return this.value == val; }).remove();
}
like image 134
Nick Craver Avatar answered Jul 28 '26 14:07

Nick Craver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!