Nati323 Posted May 6, 2015 Share Posted May 6, 2015 (edited) 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 May 6, 2015 by Nati323 Link to comment Share on other sites More sharing options...
Ingolme Posted May 6, 2015 Share Posted May 6, 2015 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 More sharing options...
Nati323 Posted May 6, 2015 Author Share Posted May 6, 2015 hey, thanks you very much, your solution works Link to comment Share on other sites More sharing options...
Ingolme Posted May 6, 2015 Share Posted May 6, 2015 Do you understand what the problem was and how the solution works? Link to comment Share on other sites More sharing options...
Nati323 Posted May 6, 2015 Author Share Posted May 6, 2015 yes, i understand Link to comment Share on other sites More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now