In this tutorial we will create a How to Add Option in Selection List using JavaScript. This tutorial purpose is to teach how to add new options into html select tag. This will cover all the important functions that provide the basic of adding an option. I will provide a sample program to show the actual coding of this tutorial.
This tutorial is simple and easy to understand just follow the instruction I provided and you can do it without a problem. This program can be use to any kind of system if you want to add another in a select tag dynamically. I will give my best to provide you the easiest way of creating this program Adding option in Select Tag. So let's do the coding.
This is the link for the template that i used for the layout design https://getbootstrap.com/.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/> <link rel="stylesheet" type="text/css" href="css/bootstrap.css"/> </head> <body> <nav class="navbar navbar-default"> <div class="container-fluid"> </div> </nav> <div class="col-md-6 well"> <hr style="border-top:1px dotted #ccc;"/> <div class="col-md-4"> <div class="form-group"> <input type="text" id="option" class="form-control"/> <br /> </div> </div> <div class="col-md-4"> <div class="form-group"> <select id="select" class="form-control"> </select> </div> </div> </div> </body> </html>
function addSelectList(){ let select = document.getElementById('select'); let option = document.getElementById('option'); if(option.value == ""){ alert("Required Field!"); }else{ let newOption = document.createElement("option"); let newOptionValue = document.createTextNode(option.value); newOption.appendChild(newOptionValue); select.insertBefore(newOption, select.lastChildNode); option.value = ""; select.value = ""; } }
In the code we will create a method called addSelectList(), this will be the only function we will needed to add options. In the first line of code inside the method we will create two variables, this two will only bind a selection element. Next we will add a conditional statement that will only prevent you to add a null value, otherwise it will continue to run the code.
In the next couple of code we create a variable that will create a new element called newOption, this will act a the parent node. Next is we create a variable that will set the value of the child element called newOptionValue. Within this two variable we just only append the child element value into the parent element in order to add new option in the select tag.
The How to Add Option in Selection List using JavaScript source code that I provide can be download below. Please kindly click the download button.
There you have it we successfully created How to Add Option in Selection List using JavaScript. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!
More Tutorials for JavaScript Language