DelphiFAQ Home Search:

Javascript to clear a listbox

 

commentsThis article has not been rated yet. After reading, feel free to leave comments and rate it.

Question:

How can I clear a listbox using Javascript?

Answer:

Use the code below. Call it by passing the listbox object to function clearlistbox()

function clearlistbox(lb){
  for (var i=lb.options.length-1; i>=0; i--){
    lb.options[i] = null;
  }
  lb.selectedIndex = -1;
}


// call it like this
clearlistbox(listbox1);

Comments:

2007-04-17, 11:16:10
anonymous from United States  
Now that's slick! I love one line solutions.
2007-10-18, 21:18:50   (updated: 2007-10-18, 21:23:27)
saralstalin@yahoo.co.in from India  
If there are selected items in the listbox, which you are trying to clear

lb.options.length = 0; will throw 'unspecified error' in IE6.
You can modify the function as

function clearlistbox(lb){
try
{
lb.options.length = 0;
}
catch(e)
{
clearlistbox(lb);
}
}
2007-10-18, 21:21:00
anonymous from India  
If there are selected items in the listbox, which you are trying to clear

lb.options.length = 0; will throw 'unspecified error' in IE6.
You can modify the function as

function clearlistbox(lb){
try
{
lb.options.length = 0;
}
catch(e)
{
clearlistbox(lb);
}
}
2008-05-09, 05:54:12
anonymous from Spain  
if will throw and erro if there are selected items...
lb.selectedIndex = -1;
lb.options.length = 0;
2010-02-01, 23:56:08
anonymous from India  
tfghfch h
2012-11-12, 03:54:25
anonymous from United States  

 

 

NEW: Optional: Register   Login
Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option, or post under a registered account.
 

Show city and country
Show country only
Hide my location
You can mark text as 'quoted' by putting [quote] .. [/quote] around it.
Please type in the code:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity.
The owner of this web site reserves the right to delete such material.

photo Add a picture: