Add/Remove Options to Select-Multiple Box from a TextBox using Javascript

by Sasikumar 2014-02-20 14:12:55

To add/remove options to a multiple select box using javascript
<html>
<head>
<title>Add/Remove option to Select Box Multiple</title>
<script type="text/javascript">
function addRows()
{
var displayname = document.getElementById('displayname').value;
var optionvalue = document.getElementById('optionvalue').value;
if(displayname!="" && optionvalue!="")
{
var option = document.createElement("option");
option.text = displayname;
option.value = optionvalue;
var select = document.getElementById("selectmultiple");
select.appendChild(option);

document.getElementById('displayname').value = "";
document.getElementById('optionvalue').value = "";
}
else
{
if(displayname=="")
alert("Enter Value to display");
if(optionvalue=="")
alert("Enter Value to option");
}
}

function removeRows()
{
var x = document.getElementById("selectmultiple");
x.remove(x.selectedIndex);
}
</script>
</head>
<body>
<h1>Add/Remove option to Select Box Multiple</h1>
<div>
<div style='padding-left:15px; float:left; width:20%;'>
<input type="text" id="displayname" name="displayname" placeholder="Value To Display" /><br />
<input type="text" id="optionvalue" name="optionvalue" placeholder="Value To Option" />
</div>
<div style="float:left; width:10%;">
<input type="button" value="Add >>" class="green_button" onClick="addRows()" /><br /><br />
<input type="button" value="<< Remove" class="red_button" onClick="removeRows()" />
</div>
<div class="element_content" style='float:left; width:25%;'>
<select id='selectmultiple' name='selectmultiple' size="0" style="width:90%; height:auto;" multiple ></select>
</div>
</div>
</body>
</html>


Output of the above code:
Screenshot.png
1023
like
0
dislike
0
mail
flag

You must LOGIN to add comments