Rooney
Rooney

Reputation: 57

Dynamic dropdown list appending values on every onchange event

I have like 3 dynamic dropdown, which are getting populated on onchange event of preceding dropdown list. onchange , I am able to populate the dropdown , but the place where am facing problem is that if I alter the selection from any dropdown , the new values get appended to the succeeding dropdown previous values instead of replacing.

Below is my code:

 Dropdown1: <select id="ddlFiles" onchange="GetNamedItems()">
              <option diasbled="disabled">Select File</option>
             </select>
 Dropdown2: <select id="ddlNamed" onchange="GetColumns()">
 Dropdown3: <select id="ddlColumn" onchange="GetColumnsY()">

 function GetNamedItems()
 {
 for (var i=0; i <namedItem.length;++i)
 {

  var list =  document.getElementById('ddlNamed');
  var newListItem = document.createElement('OPTION');  
  var listInfo=namedItem[i];

  var box = listInfo;
 newListItem.text = box;
 newListItem.value = box;
 list.add(newListItem); 
 }}

Similarly for rest of the dropdowns.

Upvotes: 0

Views: 1730

Answers (4)

Spokey
Spokey

Reputation: 10994

Remove the content before appending the new one

function GetNamedItems() {

  var list = document.getElementById('ddlNamed');
  list.innerHTML = '<option diasbled="disabled">Select File</option>';

  for (var i = 0; i < namedItem.length; ++i) {
    var newListItem = document.createElement('OPTION');
    var listInfo = namedItem[i];
    var box = listInfo;

    newListItem.text = box;
    newListItem.value = box;

    list.add(newListItem);

  }

}

Upvotes: 1

Rooney
Rooney

Reputation: 57

Working code:

function GetNamedItems() {

 var list = document.getElementById('ddlNamed');

                   $('#ddlNamed').find('option:gt(0)').remove();


for (var i = 0; i < namedItem.length; ++i) {
var newListItem = document.createElement('OPTION');
var listInfo = namedItem[i];
var box = listInfo;

newListItem.text = box;
newListItem.value = box;

list.add(newListItem);

}

}

Upvotes: 0

yk1007
yk1007

Reputation: 151

not sure about your question. Try to use .remove() before appending the new one

$(select).remove();

Upvotes: 0

Pat Dobson
Pat Dobson

Reputation: 3299

I had exactly this issue yesterday with a form reset function.

The key is:

$(select).empty();

and then repopulate the drop downs . . .

Upvotes: 0

Related Questions