Home Javascript JavaScript add method
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

JavaScript add method

Advertisement
The add() method is used to add an option to a dropdown list. Here in this example we have added an option to the select tag by using the add() method.

JavaScript add method

     

The add() method is used to add an option to a dropdown list. Here in this example we have added an option to the select tag by using the add() method.

Syntax:

 Object_of_select.add(option,before);

option : it is the option value which is to be added into the select tag's option list and this argument is required.

before : it specifies the position of the option value to be added and it is also required while adding some option to the select tag option.

Description of example:

Here in this example we have created a dropdown list in HTML and we have added a button which will add one more option to the select tag's. This button is calling JavaScript function addNew() and will add an option by getting the select tag element object by using the method getElementById().  

<html>
  <head>
    <script type="text/javascript">
	function addNew(name,val){
	  var opt = new Option(name, val);
	  document.getElementById("myselect").add(opt,undefined);
	}
     </script>
  </head>
  <body>
     <select id="myselect">
	<option value="1">Vineet</option>
	<option value="2">Sandeep</option>
	<option value="3">Vinod</option>
	<option value="4">Amar</option>
     </select>
     <button onClick="addNew('Kumar','5');this.disabled=true;">
       Add
     </button>
  </body>
</html>

Output:

When you will run this HTML page on the browser you will see that it contains only four elements into it.

Now when you will click on the "Add" button it will add one more option to the list named with the "kumar" at the "5" position.

Download Source Code

     

Advertisement

Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: January 29, 2009

Ask Questions?    Discuss: JavaScript add method  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com