最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Replace Select Box Options With JSON Result - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

2 Answers 2

Reset to default 7

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

//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));
    } 
发布评论

评论列表(0)

  1. 暂无评论