Suppose a list of options is available,how to update the <select>
with new ones?
views:
264answers:
3
+2
A:
$('#comboBx').append($("<option></option>").attr("value",key).text(value));
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.
Edit
If you need to keep the first option and remove all other then you can use
var firstOption = $("#cmb1 option:first-child");
$("#cmb1").empty().append(firstOption);
rahul
2009-11-26 04:16:08
You didn't remove the old options?
Mask
2009-11-26 04:20:18
Do you want to clear the old ones o just add new options to the existing options?
rahul
2009-11-26 04:27:24
yes,I want to clear the old ones except the first one.
Mask
2009-11-26 04:29:30
+5
A:
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
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
CMS
2009-11-26 04:21:53
@Crescent: Yeah, you're completely right, the lack of sleep is killing me hehe I haven't actually re-read my post :-) ... editing...
CMS
2009-11-26 05:44:19
A:
I had a sample of something similar a while ago. http://commadot.com/jquery/textToSelect.php
Glen Lipka
2009-11-26 05:40:02