how to change options of select with jquery

how to change options of select with jquery  using -'jquery,select,options'

asked Sep 21, 2015 by deepak
0 votes

5 Answers

0 votes

You can remove the existing options by using the empty method, and then add your new options:

var option = $('').attr("value", "option value").text("Text");

If you have your new options in an object you can:

var newOptions = {"Option 1": "value1",
  "Option 2": "value2",
  "Option 3": "value3"

var $el = $("#selectId");
$el.empty(); // remove old options
$.each(newOptions, function(value,key) {
     .attr("value", value).text(key));

Edit: For removing the all the options but the first, you can use the :gt selector, to get all the option elements with index greater than zero and remove them:

$('#selectId option:gt(0)').remove(); // remove all options, but not the first 
answered Sep 21, 2015 by santosh soni
0 votes

I threw CMS's excellent answer into a quick jQuery extension:

(function($, window) {
  $.fn.replaceOptions = function(options) {
    var self, $option;

    self = this;

    $.each(options, function(index, option) {
      $option = $("")
        .attr("value", option.value)
})(jQuery, window);

It expects an array of objects which contain "text" and "value" keys. So usage is as follows:

var options = [
  {text: "one", value: 1},
  {text: "two", value: 2}

answered Sep 21, 2015 by android_master
0 votes

where comboBx is your combo box id.

or you can append options as string to the already existing innerHTML and then assign to the select innerHTML.


If you need to keep the first option and remove all other then you can use

var firstOption = $("#cmb1 option:first-child");
answered Sep 21, 2015 by abhimca2006
0 votes

For some odd reason this part

$el.empty(); // remove old options

from CMS solution didn't work for me, so instead of that I've simply used this

el.html(' ');

And it's works. So my working code now looks like that:

var newOptions = {
 "Option 1":"option-1",
 "Option 2":"option-2"
var $el = $('.selectClass');
$el.html(' ');
$.each(newOptions, function(key, value) {
 .attr("value", value).text(key));
answered Sep 21, 2015 by deepak07.s
0 votes

If for example your html code contain this code:

In order to change the list of option inside your select, you can use this code bellow. when your name select named selectId.

var option = $('').attr("value", "option value").text("Text");

in this example above i change the old list of option by only one new option.

answered Sep 21, 2015 by santosh soni