Dynamically Add and Remove value to dropdown Javascript Example Program
Dynamically add & remove values to dropdownlist in javascript:
[html]
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My Jsp</title>
</head>
<body>
<br>
<br> Javadomain.in – Dropdown dynamic Values Add and Remove
<br>
<br>
<script type="text/javascript">
function addMe() {
var textValue = document.getElementById("txtId").value;
var ddlstSize = document.getElementById("ddlstId").length;
document.getElementById("ddlstId").options[ddlstSize] = new Option(
textValue, textValue);
//document.getElementById("ddlist").add(new Option(val,val));
alert(textValue + " is Added successfully");
}
function removeMe() {
var ddlstValue = document.getElementById("ddlstId");
var selectedVal = ddlstValue.options[ddlstValue.selectedIndex].value;
var position = document.getElementById("ddlstId").selectedIndex;
document.getElementById("ddlstId").remove(position);
alert(selectedVal + " is Removed Successfully");
}
function checkDuplicate() {
var ddlstSize = document.getElementById("ddlstId").length;
var txtVal = document.getElementById("txtId").value;
if(ddlstSize==0){
addMe();
}else{
if (txtVal.length == 0) {
alert("Please enter any value");
} else {
for ( var i = 0; i < ddlstSize; i++) {
if (document.getElementById("ddlstId").options[i].value == txtVal) {
var alertValue = confirm("Value exist, Do you want to add again ?");
if (alertValue == true) {
addMe();
break;
} else {
break;
}
} else {
if (i == ddlstSize – 1) {
addMe();
break;
} else {
continue;
}
}
}}
}
}
</script>
<select id="ddlstId" name="ddlstId">
<option value="FileHandling">FileHandling</option>
<option value="String">String</option>
<option value="Collections">Collections</option>
<option value="Classes">Classes</option>
<option value="Interface">Interface</option>
</select>
<br>
<br>
<input type="text" name="txtName" id="txtId" />
<br>
<br>
<input type="button" value="Add" onclick="checkDuplicate()">
<input type="button" value="Remove" onclick="removeMe()">
</body>
</html>
[/html]
Output:
Run the above program,
You can see the existing dropdown values,
New value(Method) added successfully,
Once the value added you can see the dropdown like this,
If we try to add the same value, we will get confirmation box, if you give ok then duplicate value will be added again,
Removing the value collections,
Recommended Javascript Books: