Jump to content

Select Object, Problem with remove() Method.


Nati323

Recommended Posts

hey all,

i have a problem with the remove() method, i will explain the all thing that i want to do...

i have the next HTML code:

Choose Category: <select class="form-control" name="cid" id="cid" onchange="showSubCat(this.options[this.selectedIndex].value);">	<option value="4">Category one</option>	<option value="8">Category two</option></select>Sub Category: <select class="form-control" name="sid" id="sid"></select>

now, i want when user select Category (First Select Element) I will update the second select (Sub Category) by an array, i have this array:

var scats = [];scats[4] = [];scats[4][0] = ['one', 7];scats[4][1] = ['two', 8];scats[4][2] = ['three', 12];scats[4][3] = ['four 2', 13];scats[8] = [];scats[8][0] = ['one', 11];

and when user select Main Category, the next function run:

function showSubCat (cId) {	var option, sCatSelect = document.getElementById('sid');	var i, len = sCatSelect.options.length;	for (i = 0; i < len; i++) {		sCatSelect.options.remove(i);	}	len = scats[cId].length;	for (i = 0; i < len; i++) {		option = document.createElement("option");		option.text = scats[cId][i][0];		option.value = scats[cId][i][1];		sCatSelect.add(option , i);	}} 

so, the data is update good, but when i choose first time the first option (in the first select element), and after that the second option, its not remove the all options, always stay 2 from the first choose, what is my problem?

Edited by Nati323
Link to comment
Share on other sites

The problem is that when you remove an option, options.length changes, and the indices also change.

 

Here's your option list:

 

0. Option 1 <- i = 0

1. Option 2

2. Option 3

3. Option 4

 

After the first iteration:

 

0. Option 2

1. Option 3 <- i = 1

2. Option 4

 

After the second iteration:

 

0. Option 2

1. Option 4

<- i = 2

 

What you can do to solve it is this:

while(sCatSelect.options.length) {    sCatSelect.options.remove(0);}
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...