Friday, March 13, 2009

Javascript : Add / Remove <option> to / from <select>

How to add or remove <option> to or from</select>

The technique used for this works for DOM complaint browsers. i.e. works in IE 6.0+, Firefox 1.0+, Safari 3 and Opera.

First step is lets write code for SELECT box.

<select id="selbox" name="selbox">
<option value="1">Text 1</option>
<option value="2">Text 2</option>
</select>


Next step is to write javascript for adding.

function addoption(){
var op = document.createElement('option');
var elSel = document.getElementById('selbox');

op.text = "Sample Text"; //write text for option.
op.value = "val"; //write value for option.

try{
elSel.add(op,null); //in IE won't work.
}
catch (er){
elSel.add(op); //for IE.
}
}


Thirs step is to write javascript for removing option which is selected.

function removeoption(){
var elSel = document.getElementById('selbox');

var i;
for (i = elSel.length - 1; i>=0; i--) {
if (elSel.options[i].selected) {
elSel.remove(i);
}
}
}


This was the complete sample code which will help you out to get learn. I have code which is more generic which i will write below :


<html>
<head>
<title>Javascript Add / Remove options from select.</title>
<script type="text/javascript">
<!--
var _doc = document;

var uloki = {
addoption: function(txtb,selb){
var em=_doc.getElementById(txtb).value;
var elSel=_doc.getElementById(selb);
var te= _doc.createElement('option');
te.text = em; te.value = em;
if(em != "" ){
try{
elSel.add(te,null); //in IE it wwont work
}
catch (er){
elSel.add(te); //for IE
}
_doc.getElementById(txtb).value="";
}
},
removeoption: function(selb){
var elSel = _doc.getElementById(selb);
var i;
for (i = elSel.length - 1; i>=0; i--) {
if (elSel.options[i].selected) {
elSel.remove(i);
}
}
}
};
//-->
</script>
</head>
<body>

<input type="text" name="tbox" id="tbox">
<input type="button" value=" Add " onclick="uloki.addoption('tbox','selb')">
<br/><br/>

<table>
<tr>
<td>
<select name="selb" id="selb" size="4">
<option value="dt">Default Text</option>
</select>
</td>
<td> <input type="button" value="Remove Selected" onclick="uloki.removeoption('selb')"> </td>
</tr>
</table>
</body>
</html>


I think you have gone through the example explained and also sample i made. Well remember size of select box should be always more than 2. if you remove size or keep it below 2 then it wont function properly.

So this was how it works : Javascript Add / Remove <option> tag from / to <select> tag.


Thanks & Put comments if you found bugs / or even if it helped you.

No comments:

Post a Comment