How to Add Dynamically Option in JavaScript

0 26,736

In this post, I am going to tell you how to dynamically add options from the front end in javascript. Javascript is a client-side object-oriented programming language it is used to add dynamic features and interactive functionality to websites. and it is a dialect of the ECMAScript standard. The source code will include explanations of the javascript functionality. in the current example HTML, CSS and Javascript code written in a different file.

Creating Index Page

in this step we are going to create index page where add dynamically option using javascript. in this page we create simple form and a button to perform add option from front-end. copy and paste below code and save it as index.html.

<!DOCTYPE html>
<html lang="en">
	<head>
		<title>How to Add Dynamically Option in javaScript</title>
		<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
		<link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
					<style>
		body{
			margin-top:65px;
		}
		.well{
			-webkit-box-shadow: -5px 3px 28px 1px rgba(179,179,179,1);
			-moz-box-shadow: -5px 3px 28px 1px rgba(179,179,179,1);
			box-shadow: -5px 3px 28px 1px rgba(179,179,179,1);
			    padding: 50px;
			margin-bottom: 20px;
			background-color: #ffffff;
			border: 1px dotted #a20000;
		}

	</style>
		
	</head>
<body>

	<div class="col-md-3"></div>
	<div class="col-md-6 well">
		
		<div class="col-md-2"></div>
		<div class="col-md-8">
			<div class="form-inline">
				<center><label>Add Product Category </label>
				<input type="text" id="option" class="form-control"/></center>
			</div>
			<br />
			<center><button type="button" class="btn btn-success" onclick="addOption()">Add option</button></center>
			<br />
			<div class="form-group">
				<select id="select" class="form-control">
					<option value="">--Select an Category--</option>
				</select>
			</div>
		</div>
	</div>
<script src="js/script.js"></script>
</body>
</html>

Creating Javascript File

in this step we are going to create javascript function to add option dynamically from front-end. copy the below code and save it as script.js in your project folder.

function addOption(){
	var select = document.getElementById('select');
	var option = document.getElementById('option');
	
	if(option.value == ""){
		alert("Please enter something first!");
	}else{
		var newOption = document.createElement("option");
		var newOptionValue = document.createTextNode(option.value);
		
		newOption.appendChild(newOptionValue);
		select.insertBefore(newOption, select.lastChildNode);
		
		option.value = "";
		select.value = "";
	}
}

If you facing any type of problem with this source code then you can Download the Complete source code in zip Formate by clicking the below button Download Now otherwise you can send Comment.

Download Source Code

Leave A Reply

Your email address will not be published.