Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace Select Box Options With JSON Result

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>
like image 1000
Get Off My Lawn Avatar asked May 14 '26 19:05

Get Off My Lawn


2 Answers

Use .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

like image 140
PSL Avatar answered May 17 '26 08:05

PSL


//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));
    } 
like image 26
Nikola Mitev Avatar answered May 17 '26 10:05

Nikola Mitev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!