removing entries from listbox on the fly
Hello guys, I need a little help with javascript.
I have two identical listboxes, when a user makes a selection in one list box, the same item must be removed from both the listboxes (to prevent duplication). This process must occur on the fly with onchange function and not using any additional buttons.
I am not sure how to implement this. Any help would be appreciated.
Re: removing entries from listbox on the fly
Can you post your current code for removing item in a single listbox so we can see where you are at the moment with it?
Re: removing entries from listbox on the fly
not exactly what you're asking for, but you might want to take a look at this tutorial: http://www.mredkj.com/tutorials/tutorial005.html
Re: removing entries from listbox on the fly
As suggested by JL, I employed this for removal in the same listbox
Code:
var lid1 = document.getElementById(id1);
var i;
for (i = lid1.length - 1; i>=0; i--) {
if (lid1.options[i].selected) {
lid1.remove(i);
}
}
I don't know how to search for the selected item in another listbox and remove it too.
Re: removing entries from listbox on the fly
I'll make you hit your head on your desk, assuming both listboxes have identical amount of items:
Code:
var lid1 = document.getElementById(id1);
var lid2 = document.getElementById(id2);
/* just showing how to make the code a little bit shorter here */
for (var i = lid1.length; i > 0; --i) {
if (lid1.options[i].selected) {
lid1.remove(i);
lid2.remove(i);
}
}
However, if the items are not in the same order in the other listbox then things get more complex: the only solution is to loop through each item in the second listbox and remove if a match is found.
Re: removing entries from listbox on the fly
The lists are in identical orders and this works fine, but I would still prefer the way where the item is searched one by one in a loop until a match is found (to be failsafe). I have been trying to that but I am failing. Can you please help me?
Additional remarks: The above script (strangely) is removing more than one element from the listbox; most often those preceding the selected one.