Click to See Complete Forum and Search --> : deleting items in a list
anguilla
02-04-2003, 11:55 AM
I am building a piece of code so the user can add/delete/move up or move down elements in a list. I have the add working but I'm having some problems with the delete. When a item in the list is selected, the items seems to get deleted BUT there is still a "blank" space in the list, so it seems like the text got deleted but not the value !
Any suggestions ?
Code:
function Remove(dest) {
for ( i = 0; i < dest.length; i++ ) {
if ( dest[i].selected && dest[i] != "" ) {
dest[i].value = "";
dest[i].text = "";
}
}
}
havik
02-04-2003, 12:07 PM
It deletes the text only because your setting it to "", and not completely removing it. You need to delete the selected value by first finding it, then shifting everything over one.
Example:
array[0] = "hello";
array[1] = "This";
array[2] = "is";
array[3] = "a";
array[4] = "test";
now we want to delete "is" properly.
"is" is located at array[2], all the indexes before this are ok, but all the ones after need to be shifted down one.
array[2] = array[3]
array[3] = array[4]
array[4] = "" // or whatever you wish to do with this
It is very simple to create a for loop to do this, you might need a temp variable when shifting the values.
anguilla
02-04-2003, 04:24 PM
got it too work. Thanks. :)
slightly different than you suggested but it works (IE 5.5)
function Remove(dest) {
if ( dest.length != 0 ) {
if ( dest.selectedIndex == -1 ) {
alert('You must pick a element to remove !!');
}
else {
for ( var i = 0; i < dest.length; i++ ) {
if ( dest[i].selected ) {
dest[i].text = "";
dest[i] = null;
}
}
}
}
else {
alert ('There are no elements to delete !!');
}
}
havik
02-04-2003, 04:30 PM
Just curious, if you try to access the dest[i] that was set to null, do you get nothing or do you get the text for the next one (as I believe it should work). Like a dynamically sized array.
But if it works, it works eh? :D
Havik
anguilla
02-05-2003, 06:08 AM
To be honest, I don't know if the actually values are what I expect. I'll be working on that piece of code today. As of now, my array does increase (add) and decrease (remove) accordingly. One step at a time .... :)