Dynamically Add and Remove value to dropdown Javascript Example Program

Dynamically add & remove values to dropdownlist in javascript:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>My Jsp</title>
	<br> Javadomain.in - Dropdown dynamic Values Add and Remove
	<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;
			alert(selectedVal + " is Removed Successfully");
		function checkDuplicate() {
			var ddlstSize = document.getElementById("ddlstId").length;
			var txtVal = document.getElementById("txtId").value;
			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) {
						} else {
					} else {
						if (i == ddlstSize - 1) {
						} else {
	<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>
	<input type="text" name="txtName" id="txtId" />
	<input type="button" value="Add" onclick="checkDuplicate()">
	<input type="button" value="Remove" onclick="removeMe()">


Run the above program,

Dynamic drop down list

You can see the existing dropdown values,

Dynamic drop down value expanded

New value(Method) added successfully,

dynamically adding value to dropdown

Once the value added you can see the dropdown like this,

dropdown after value added

If we try to add the same value, we will get confirmation box, if you give ok then duplicate value will be added again,

adding duplicate value to dropdown

Removing the value collections,

removing value from dropdown list

Recommended Javascript Books:

1,971 total views, 1 views today

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.