1. ホーム
  2. jquery

[解決済み] [Solved] How to change options of <select> with jQuery?

2022-03-30 02:03:53

Question

Suppose a list of options is available, how do you update the <select> with new <option> s?

How to solved?

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

var option = $('<option></option>').attr("value", "option value").text("Text");
$("#selectId").empty().append(option);

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(key,value) {
  $el.append($("<option></option>")
     .attr("value", value).text(key));
});

Edit: For removing the all the options but the first, you can use the :gt セレクタを使用すると、すべての option インデックスが0より大きい要素、および remove それらを

$('#selectId option:gt(0)').remove(); // remove all options, but not the first