views:

264

answers:

3

Suppose a list of options is available,how to update the <select> with new ones?

+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
You didn't remove the old options?
Mask
Do you want to clear the old ones o just add new options to the existing options?
rahul
yes,I want to clear the old ones except the first one.
Mask
+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
How to remain the first option when empty()?
Mask
+1 for `$('#selectId option:gt(0)').remove();`
Rakesh Juyal
That is *not* a JSON object! It is a JavaScript object ;)
Crescent Fresh
@Crescent: Yeah, you're completely right, the lack of sleep is killing me hehe I haven't actually re-read my post :-) ... editing...
CMS
A: 

I had a sample of something similar a while ago. http://commadot.com/jquery/textToSelect.php

Glen Lipka