0

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.

she_be_me
  • 79
  • 1
  • 3
  • 9

2 Answers2

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 
        }));
    });
Afnan Ahmad
  • 2,492
  • 4
  • 24
  • 44
2

Check this,

$(document).ready(function(){
         $("#test").append($('<option>', {value: 2,text: 'Two'}));
        });
<script src="https://ajax.googleapis.com/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.

Rahul
  • 18,271
  • 7
  • 41
  • 60