JavaScript getElementById select

This page discusses - JavaScript getElementById select

JavaScript getElementById select

JavaScript getElementById select

        

We can use document.getElementById() over the <select> tag to perform any operation with the selected value as a option. We will be describing you here to use getElementById with select by using a very simple example. In this example we have created two dropdown list by using <select> tags.

We have defined two JavaScript functions selectOption() and selectTypeOption() which will be invoked when their respective select options are selected or selection is changed.

 function selectOption() {
   alert("You have selected site "+ document.getElementById("listSelect").value);
  }

One and only one line in the selectOption() function gets the element's reference with the document.getElementById() and after having the reference to the selected list we can show the selected option as document.getElementById().value. Similarly we have shown the selected option in the selectTypeOption() function.

  function selectTypeOption() {
   alert("You have selected type "+ document.getElementById("typeSelect").value);
  }

Here is the full description of code as follows :

<html>
 <head>
   <title>
     getElementBuId Select example
   </title>
   <script language="javascript" >
      function selectOption() {
	alert("You hvae selected site "+ 
           document.getElementById("listSelect").value);
      }
      function selectTypeOption() {
	alert("You have selected type "+
           document.getElementById("typeSelect").value);
      }
   </script>
  </head>
  <body>
   <div style="background: #DFDFFF; width:'100%';" align="center">
    <font color="#000080" size="12pt">
    <b>getElementById in &lt;select&gt;</b>
    </font>
   </div>
   <p>&nbsp;</p>
     Select Type : 
    <select id="typeSelect" style="width:150px;"
                                 onChange="selectTypeOption();">
	<option value="Technologies">Technologies</option>
	<option value="News">News </option>
	<option value="Job Search">Job Search</option>
    </select>
    <p>&nbsp;</p>
       Select Site : 
      <select id="listSelect" style="width:150px;" 
                                 onChange="selectOption();">
	<option value="Rose India">Rose India</option>
	<option value="News Track India">News Track India</option>
	<option value="Cool Jobs">Cool Jobs</option>
      </select>
   </body>
</html>

Output :

Select any type

Suppose we select type News

An alert() message would be shown with the message "You have selected type News".

Now if we select Site from the list.

It will float an alert() method with the message "You have selected site News Track India".

If you want to download full source code then you can freely download the source code from the following link :

Download Source Code