Home Javascript JavaScript add method



JavaScript add method
Posted on: January 29, 2009 at 12:00 AM
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

     

Related Tags for JavaScript add method:
clistselectiomethodsedpdodropdowntagusingthisexampleaddtoexamdropoptioneliuseddeinmddadmedodownxaxampsaddedishamplssthavstpleplono


More Tutorials from this section

Ask Questions?    Discuss: JavaScript add method  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.