I have a select box, and when I click on a button, an ajax request is made, and it returns json object the object contains a new list of options for the select box. Is there any way that I can remove all the options from the select box and replace them with the new list?
<select id="cat-0" >
<option value="0">Select One...</option>
<option value="1">Text 1</option>
<option value="2">Text 2</option>
<option value="3">Text 3</option>
</select>
I have a select box, and when I click on a button, an ajax request is made, and it returns json object the object contains a new list of options for the select box. Is there any way that I can remove all the options from the select box and replace them with the new list?
<select id="cat-0" >
<option value="0">Select One...</option>
<option value="1">Text 1</option>
<option value="2">Text 2</option>
<option value="3">Text 3</option>
</select>
Share
Improve this question
asked May 30, 2013 at 20:30
Get Off My LawnGet Off My Lawn
36.4k46 gold badges197 silver badges374 bronze badges
2
- Yes of course there is. Have you tried anything? – Bergi Commented May 30, 2013 at 20:32
- Lets see the format of that JSON data! – tymeJV Commented May 30, 2013 at 20:34
2 Answers
Reset to default 7Use .html()
to insert new options clearing the existing ones.
$('#cat-0').html(newOptions);
But of course you need to construct options from your JSON Data something like this.
var json=[{value:'1', text:'Option1'},
{value:'2', text:'Option2'},
{value:'3', text:'Option3'}];
var options=$('<select/>');
$.each(json, function(id, ob){
options.append($('<option>',
{value:ob.value,
text:ob.text}));
});
$('#cat-0').html(options.html());
Fiddle
//Clear the select list
$('#cat-0').empty();
//then fill it with data from json post
$.each(data, function(key, value) {
$('#cat-0')
.append($("<option></option>")
.attr("value",key)
.text(value));
}