»
EnglishFrenchVietnamese

Print - Add Remove Options - JavaScriptBank.com

Full version: jsB@nk » Form » Dropdown » Add Remove Options
URL: https://www.javascriptbank.com/add-remove-options.html

Add Remove Options © JavaScriptBank.comAdd or remove objects in a select list, using the DOM. This JavaScript was written to work with DOM Level 1 and DOM Level 2 capable browsers, with try/catch logic included for IE use.

Full version: jsB@nk » Form » Dropdown » Add Remove Options
URL: https://www.javascriptbank.com/add-remove-options.html



JavaScript
<script language="javascript"><!--// Created by: Keith Jenci :: http://www.mredkj.com/var count1 = 0;var count2 = 0;function insertOptionBefore(num) {  var elSel = document.getElementById('selectX');  if (elSel.selectedIndex >= 0) {    var elOptNew = document.createElement('option');    elOptNew.text = 'Insert' + num;    elOptNew.value = 'insert' + num;    var elOptOld = elSel.options[elSel.selectedIndex];      try {      elSel.add(elOptNew, elOptOld); // standards compliant; doesn't work in IE    }    catch(ex) {      elSel.add(elOptNew, elSel.selectedIndex); // IE only    }  }}function removeOptionSelected() {  var elSel = document.getElementById('selectX');  var i;  for (i = elSel.length - 1; i>=0; i--) {    if (elSel.options[i].selected) {      elSel.remove(i);    }  }}function appendOptionLast(num) {  var elOptNew = document.createElement('option');  elOptNew.text = 'Append' + num;  elOptNew.value = 'append' + num;  var elSel = document.getElementById('selectX');  try {    elSel.add(elOptNew, null); // standards compliant; doesn't work in IE  }  catch(ex) {    elSel.add(elOptNew); // IE only  }}function removeOptionLast() {  var elSel = document.getElementById('selectX');  if (elSel.length > 0)  {    elSel.remove(elSel.length - 1);  }}//--></script><!--    This script downloaded from www.JavaScriptBank.com    Come to view and download over 2000+ free javascript at www.JavaScriptBank.com-->


HTML
<form><select id="selectX" size="8" multiple="multiple">  <option value="original1" selected="selected">Original 1</option>  <option value="original2">Original 2</option></select><br><input value="Insert Before Selected" onclick="insertOptionBefore(count1++);" type="button"><br><input value="Remove Selected" onclick="removeOptionSelected();" type="button"><br><input value="Append Last Entry" onclick="appendOptionLast(count2++);" type="button"><br><input value="Remove Last Entry" onclick="removeOptionLast();" type="button"></form><!--    This script downloaded from www.JavaScriptBank.com    Come to view and download over 2000+ free javascript at www.JavaScriptBank.com-->