Sunday, July 10, 2011

Add or remove list box items dynamically in javascript

How to add or remove list box items dynamically using JavaScript


Following example shows you how to add or remove list items in HTML option element in JavaScript

In some occasions you may want to add one or more options to HTML select box/list box and some times remove items from a HTML dropdown/list box. You can use a simple JavaScript code to add/remove options from a HTML select element. following examples describe how to dynamically change items in a dropdown box.

1. How to Add elements/options to a list box dynamically using JavaScript?

Example : Add options/items to a list box/dropdown box/list menu in javaScript You can add any item to the dropdown box but you can't duplicate list items.

Year
Option Value
Option Display Text
 

Example code for add new option to HTML select element

<HTML xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/HTML; charset=iso-8859-1" />
<title>Add Option Items </title>
<script type="text/javaScript">
function addNewListItem(){
var htmlSelect=document.getElementById('selectYear');
var optionValue=document.getElementById('txtYearValue');
var optionDisplaytext=document.getElementById('txtYearDisplayValue');

if(optionValue.value==''||isNaN(optionValue.value)){
alert('please enter option value');
optionValue.focus();
return false;
}
if(optionDisplaytext.value==''||isNaN(optionDisplaytext.value)){
alert('please enter option display text');
optionDisplaytext.focus();
return false;
}
if(isOptionAlreadyExist(htmlSelect,optionValue.value)){
alert('Option value already exists');
optionValue.focus();
return false;
}
if(isOptionAlreadyExist(htmlSelect,optionDisplaytext.value)){
alert('Display text already exists');
optionDisplaytext.focus();
return false;
}
var selectBoxOption = document.createElement("option");
selectBoxOption.value = optionValue.value;
selectBoxOption.text = optionDisplaytext.value;
htmlSelect.add(selectBoxOption, null);
alert("Option has been added successfully");
return true;

}
function isOptionAlreadyExist(listBox,value){
var exists=false;
for(var x=0;x<listBox.options.length;x++){
if(listBox.options[x].value==value || listBox.options[x].text==value){
exists=true;
break;
}
}
return exists;
}
</script>
</head>

<body>
<table border="0" align="left">
<tr>
<td align="right">Year</td>
<td align="left"><select name="selectYear" id="selectYear">
<option value="2000">2000</option>
<option value="2001">2001</option>
<option value="2002">2002</option>
<option value="2003">2003</option>
<option value="2004">2004</option>
</select></td>
</tr>
<tr>
<td align="right">Option Value</td>
<td align="left"><input name="txtYearValue" type="text" id="txtYearValue" /></td>
</tr>
<tr>
<td align="right">Option Display Text</td>
<td align="left"><input name="txtYearDisplayValue" type="text" id="txtYearDisplayValue" /></td>
</tr>
<tr>
<td align="right">&nbsp;</td>
<td align="left"><input name="btnAddItem" type="button" id="btnAddItem" value="Add Option" onclick="javaScript:addNewListItem();" /></td>
</tr>
</table>
</body>
</HTML>

Example 2:
Animal
Option Value
Option Display Text
 

Copy and paste above code and modify it to add string values

How to check option already exists or not?

function isOptionAlreadyExist(listBox,value){
var exists=false;
for(var x=0;x<listBox.options.length;x++){
if(listBox.options[x].value==value || listBox.options[x].text==value){
exists=true;
break;
}
}
return exists;
}

  
Example 3:Add numbers to a listbox.
Even Numbers
Option Value
Option Display Text
 

How to add new option to a HTML select element?

var htmlSelect = document.createElement("selectAnimals");//HTML select box
var optionValue=document.getElementById('txtValue');
var optionDisplaytext=document.getElementById('txtDisplayValue');

var selectBoxOption = document.createElement("option");//create new option
selectBoxOption.value = optionValue.value;//set option value
selectBoxOption.text = optionDisplaytext.value;//set option display text
htmlSelect.add(selectBoxOption, null);//add created option to select box.

2. How to remove options/items from listbox dynamically using JavaScript?

Example 1 : Remove options/items from a list box/dropdown box/list menu

Example 1:
Select a year to remove
 


Example code for remove list items from a HTML select element

<HTML xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/HTML; charset=iso-8859-1" />
<title>Remove Select Options </title>
<script type="text/javaScript">
function removeListItem(){
var htmlSelect=document.getElementById('selectYear');

if(htmlSelect.options.length==0){
alert('You have removed all options');
return false;
}
var optionToRemove=htmlSelect.options.selectedIndex;
htmlSelect.remove(optionToRemove);
alert('The selected option has been removed successfully');
return true;
}
</script>
</head>

<body>
<table border="0" align="left">
<tr>
<td align="right">select a year to remove </td>
<td align="left"><select name="selectYear" id="selectYear">
<option value="2000" selected="selected">2000</option>
<option value="2001">2001</option>
<option value="2002">2002</option>
<option value="2003">2003</option>
<option value="2004">2004</option>
</select></td>
</tr>
<tr>
<td align="right">&nbsp;</td>
<td align="left"><input name="btnRemoveItem" type="button" id="btnRemoveItem" value="Remove Option" onClick="javaScript:removeListItem();" /></td>
</tr>
</table>
</body>
</HTML>

Example 2 :Select a country and click on Remove Country button to delete them from the list menu.
Select a country to remove
 


How to remove list item from list box?

var htmlSelect=document.getElementById('selectYear');//HTML select box
var optionToRemove=htmlSelect.options.selectedIndex;//get the selected index
htmlSelect.remove(optionToRemove);//remove option from list box

3.How to remove options/items from HTML list menu dyanamically using JavaScript?

Example 1 : Remove options/items from a dropdown box/list menu.

Example 1:
Select a Mobile Phone to remove
 

How to remove items from HTML select menu?

<HTML xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/HTML; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javaScript">
function removePhoneType(){
var htmlSelect=document.getElementById('selectMobilePhones');

if(htmlSelect.options.length==0){
alert('You have already removed all list items');
return false;
}

var optionToRemove=htmlSelect.options.selectedIndex;
htmlSelect.remove(optionToRemove);

if(htmlSelect.options.length>0){
htmlSelect.options[0].selected=true;
}
alert('The selected phone type has been removed successfully');
return true;
}
</script>
</head>

<body>
<table border="0">
<tr>
<td align="right">Select a Mobile Phone to remove</td>
<td align="left"><select name="selectMobilePhones" size="5" id="selectMobilePhones">
<option value="Nokia" selected="selected">Nokia</option>
<option value="Motorola">Motorola</option>
<option value="Sony Ericsson">SonyEricsson</option>
<option value="Micromax">Micromax</option>
<option value="Apple">Apple</option>
<option value="Vodaphone">Vodaphone</option>
<option value="Alcatel">Alcatel</option>
<option value="Lenovo">Lenovo</option>
<option value="Samsung">Samsung</option>
<option value="Blackberry">Blackberry</option>
<option value="LG">LG</option>
<option value="Lava">Lava</option>
<option value="Sony">Sony</option>
</select></td>
</tr>
<tr>
<td align="right">&nbsp;</td>
<td align="left"><input name="btnRemovePhone" type="button" id="btnRemovePhone" onclick="javaScript:removePhoneType();" value="Remove Phone" /></td>
</tr>
</table>
</body>
</HTML>

4. How to remove multiple options/items from a listbox dynamically using JavaScript?

Example 1 : remove multiple options/items from a list menu. You can select more than one item from the drop down box. Use shift key to select multiple items from the list menu.

Example 1:
Select one or more countries to remove
 

How to remove multiple options at once?

<HTML xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/HTML; charset=iso-8859-1" />
<title>Remove Multiple List Items</title>
<script type="text/javaScript">
function removeMultipleOptions(){
var listBox=document.getElementById("selectMultipleCountries");
if(listBox.options.length==0){
alert('You have already removed all list box items');
return false;
}
var removedOptionCount=0;
var valuesToBeRemoved=Array();

for(var x=0;x<listBox.options.length;x++){
if(listBox.options[x].selected==true){
valuesToBeRemoved.push(listBox.options[x].value);
}
}

for(var j=0;j<valuesToBeRemoved.length;j++){
removedOptionCount+=removeListItemOneByOne(listBox,valuesToBeRemoved[j]);
}

if(removedOptionCount==0){
alert('Please select one or more items to remove');
listBox.focus();
return false;
}else{
alert(removedOptionCount+' option(s) have been removed successfully');
return true;
}
}

function removeListItemOneByOne(listBox,valueToRemove){
var removed=0;
for(var i=0;i<listBox.options.length;i++){
if(listBox.options[i].value==valueToRemove){
listBox.remove(i);
removed=1;
break;
}
}
return removed;
}
</script>
</head>

<body>
<table border="0"> <tr>
<td align="right">Select one or more countries to remove</td>
<td align="left"><select name="selectMultipleCountries" size="10" multiple="multiple" id="selectMultipleCountries">
<option value="AF" selected="selected">Afghanistan</option>
<option value="AX">&Atilde;&hellip;Land Islands</option>
<option value="AL">Albania</option>
<option value="DZ">Algeria</option>
<option value="AS">American Samoa</option>
<option value="AD">Andorra</option>
<option value="AO">Angola</option>
<option value="AI">Anguilla</option>
<option value="AQ">Antarctica</option>
<option value="AG">Antigua And Barbuda</option>
<option value="AR">Argentina</option>
<option value="AM">Armenia</option>
<option value="AW">Aruba</option>
</select></td>
</tr>
<tr>
<td align="right">&nbsp;</td>
<td align="left"><input name="btnRemoveMultipleOptions" type="button" id="btnRemoveMultipleOptions" value="Remove Selected Options" onclick="javaScript:removeMultipleOptions();" /></td>
</tr>
</table>
</body>
</HTML>

5. How to interchange/swap options/items between two list boxes dynamically using JavaScript?

Example 1 : Swap options between two HTML select elements. Some times you may need to interchange list items between two drop down menus. You can use following code for swap list items from one select menu to another menu. Select one or more items from left drop down list and click on button to move them to the right. Likewise you can select items from left dropdown menu and move them to the right drop down box.

Example 1:
Available Countries Your Selection
  
 
 

How to swap/interchange list items between two dropdown boxes?

<HTML xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/HTML; charset=iso-8859-1" />
<title>Interchange/Swap List Items</title>
<script type="text/javaScript">
function moveToRightOrLeft(side){
var listLeft=document.getElementById('selectLeft');
var listRight=document.getElementById('selectRight');

if(side==1){
if(listLeft.options.length==0){
alert('You have already moved all countries to Right');
return false;
}else{
var selectedCountry=listLeft.options.selectedIndex;

move(listRight,listLeft.options[selectedCountry].value,listLeft.options[selectedCountry].text);
listLeft.remove(selectedCountry);

if(listLeft.options.length>0){
listLeft.options[0].selected=true;
}
}
}else if(side==2){
if(listRight.options.length==0){
alert('You have already moved all countries to Left');
return false;
}else{
var selectedCountry=listRight.options.selectedIndex;

move(listLeft,listRight.options[selectedCountry].value,listRight.options[selectedCountry].text);
listRight.remove(selectedCountry);

if(listRight.options.length>0){
listRight.options[0].selected=true;
}
}
}
}

function move(listBoxTo,optionValue,optionDisplayText){
var newOption = document.createElement("option");
newOption.value = optionValue;
newOption.text = optionDisplayText;
listBoxTo.add(newOption, null);
return true;
}
</script>
</head>

<body>
<div>
<ul>
<li><table border="0">
<tr>
<td colspan="4">Example 1:</td>
</tr>
<tr>
<td colspan="2">Available Countries </td>
<td colspan="2">Your Selection </td>
</tr>
<tr>
<td rowspan="3" align="right"><label>
<select name="selectLeft" size="10" id="selectLeft">
<option value="AS" selected="selected">American Samoa</option>
<option value="AD">Andorra</option>
<option value="AO">Angola</option>
<option value="AI">Anguilla</option>
<option value="AQ">Antarctica</option>
<option value="AG">Antigua And Barbuda</option>
<option value="AR">Argentina</option>
<option value="AM">Armenia</option>
<option value="AW">Aruba</option>
<option value="AU">Australia</option>
<option value="AT">Austria</option>
</select>
</label></td>
<td align="left">&nbsp;</td>
<td align="left">&nbsp;</td>
<td rowspan="3" align="left"><select name="selectRight" size="10" id="selectRight">
<option value="AF" selected="selected">Afghanistan</option>
<option value="AX">&Atilde;&hellip;Land Islands</option>
<option value="AL">Albania</option>
<option value="DZ">Algeria</option>
</select></td>
</tr>
<tr>
<td align="left">&nbsp;</td>
<td align="left"><label>
<input name="btnRight" type="button" id="btnRight" value="&gt;&gt;" onClick="javaScript:moveToRightOrLeft(1);">
</label></td>
</tr>
<tr>
<td align="left">&nbsp;</td>
<td align="left"><label>
<input name="btnLeft" type="button" id="btnLeft" value="&lt;&lt;" onClick="javaScript:moveToRightOrLeft(2);">
</label></td>
</tr>
<tr>
<td>&nbsp;</td>
<td align="left">&nbsp;</td>
<td align="left">&nbsp;</td>
<td align="left">&nbsp;</td>
</tr>
</table>
</li>
<li>
<div>
<p>Copy and paste above code and modify it to add string values <br /> <br />
<strong>How to check option already exists or not?</strong><br /><br />
function isOptionAlreadyExist(listBox,value){<br />
var exists=false;<br />
for(var x=0;x&lt;listBox.options.length;x++){<br />
if(listBox.options[x].value==value || listBox.options[x].text==value){ <br />
exists=true;<br />
break;<br />
}<br />
}<br />
return exists;<br />
}</p>
</div>
</li>
<li class="code_right"></li>
</ul>
</div>
</body>
</HTML>

 


16 comments:

Anonymous said...

Thanx.help full code......

AkoSiRenee said...

hi! but what is i am retrieving the datas from a database? how would i do it?

currently what i can do right now is to display the data inside ONE LISTBOX... and i used pure php with that.
hoping u can help me. THANKS!

Anonymous said...

thanks....i was looking for such example

Anonymous said...

simply GREATE

Ram said...

hi...

wn i copy and paste the first example to empty html page... its not working! why?

resolve for me

Tnx

Austin Kim said...

I like your samples here.

However, the last example which I was looking for need to add 'name="selectRight[]" multiple="multiple"' in order to pass all values in the form.

Also, it needs javascript that set attribute to "selected" for all values in "selectRight".

Thanks

Phạm Minh Hoàng said...

thanks you for examples. very useful

Monika said...

Great work :)
Really helped :D

MUQTHAR said...

Dear Friend

How to insert list values in to mysql database in 5th example please help me

Jorge said...

GREAT posting - Many thanks for posting this!

On example 1, how can the new entry be the SELECTED OPTION?


Anonymous said...

Thx a lot.. I was looking exasctly for this..

Anonymous said...

You people need to learn English.

Anonymous said...

how u make option do like stuff 4 me pleaz resolve all my question now thanks

kumar said...

how many days will takes to php

Anonymous said...

how to add and remove data with in two drop down box

Vũ Hoàng said...

Dưỡng da bằng gì là tốt nhất, collagen shiseido dạng viên là lựa chọn thích hợp nhất cho chị em đấy. Collagen là gì? tác dụng của collagen đối với cơ thể như thế nào. Gót chân bạn đang bị đau ư? kem trị nứt gót chân này sẽ chữa trị tốt vết thương đấy. Nám da mặt là gì? có loại kem trị nám tốt nhất nào thích hợp với tôi không? Sữa ong chúa là gì? sữa ong chúa royal jelly 1000mg là loại TPCN hỗ trợ năng lượng tốt cho cơ thể đấy. Nấm móng tay là gì? kem trị nấm móng tay chân tốt có thể trị dứt điểm bệnh được không? Ung thư là gì? thuốc điều trị ung thư có thật là tốt và có thể trị bênh ung thư không? Hiện tương rụng tóc là điều gì? có loại thuốc chống rụng tóc nào tốt không vậy ta?