admin管理员组

文章数量:1279145

I am using a form in a modal where i add new fields to the select box and would like to refresh the select box such that the new options are added to it. And this without reloading the entire page . Can someone please tell me if this is possible or not and if it is how do i go about it.

I am using a form in a modal where i add new fields to the select box and would like to refresh the select box such that the new options are added to it. And this without reloading the entire page . Can someone please tell me if this is possible or not and if it is how do i go about it.

Share Improve this question asked Feb 21, 2017 at 11:19 she_be_meshe_be_me 791 gold badge3 silver badges10 bronze badges 8
  • is it simple select dropdown or some plugin you are using – Rahul Commented Feb 21, 2017 at 11:20
  • $("form")[0].reset();? – madalinivascu Commented Feb 21, 2017 at 11:20
  • Hi, Could you pls jsFiddle or something ? – Ranjeet Commented Feb 21, 2017 at 11:20
  • Step 1: Make API call and get new options. Step 2: Update selectbox with new options – Rajesh Commented Feb 21, 2017 at 11:20
  • 1 Let us see at least the select and the new options. – Bulent Vural Commented Feb 21, 2017 at 11:22
 |  Show 3 more ments

2 Answers 2

Reset to default 5

There are multiple ways of doing this:

First if you are using jQuery this is simple like:

$("#dropdownlist").empty();

Another way can be:

for(i = dropdownlist.options.length - 1 ; i >= 0 ; i--)
{
   dropdownlist.remove(i);
}

Another simplest way can be:

document.getElementById("dropdownlist").innerHTML = "";

Now if you want to repopulate it. You can append the options with jQuery. If you have single value you can achieve it like:

$('#dropdownlist').append($('<option>', {
    value: 1,
    text: 'New option'
}));

And if it's a collection. you need to loop over it like the following snippet:

 $.each(newOptions, function (i, val) {
        $('#dropdownlist').append($('<option>', { 
            value: val.value,
            text : val.text 
        }));
    });

Check this,

$(document).ready(function(){
        	$("#test").append($('<option>', {value: 2,text: 'Two'}));
        });
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="test">
          <option value="1">One</option>
 </select>

Give it a try, it should work.

本文标签: javascripthow to refresh select box without reloading the whole form in jsStack Overflow