How To Remove Options From HTML Select Lists Using Javascript

0

When using HTML Select lists it is sometimes useful to be able to remove options from the list dynamically. Perhaps in response to interactions on the page by the user. This is easy to do with JavaScript using the custom function defined below called “SelectOptRemove”.

It takes two parameters. The first parameter “pValue” is the value of the option your want to remove. The second parameter is pId and that is the ID reference of the Select list you want to deal with.

function SelectOptRemove(pValue, pId)
{  
  // SelectOptRemove
  //
  // Removes options from a select list.
  //
  // Takes two arguments.
  //   pValue is the value to remove
  //   pId    is ID of select list
  //
  // Author  : Matt Hawkins
  // Date    : 19/04/2013
  // Website : http://www.how2code.co.uk

  var i;
  var vLen;
  var vFlag = false;
  
  // Get select element with ID=pID
  var vList = document.getElementById(pId);
  
  // Get number of options in select list
  vLen = vList.options.length;

  // Loop through each option
  for (i=0;i

Here is a link to a simple example HTML page that shows the JavaScript function removing select list options :

javascript_select_list_remove_option.html

Share.

Leave A Reply