get element by id

Forms are the most frequently used objects on dynamic web pages. There are various controls like textfields, lists etc used on the forms to get input from the user. So once you have got the user input, how do you store the values entered in the controls.

Perhaps, there are several ways to do it in JavaScript; the most straightforward way is to use the document object’s ‘getElementById’ (get element by id) method. Every control can be assigned an ID by specifying it in the ID attribute of the control. The method getElementById uses this field to retrieve the value from the control.

Syntax of getElementById

Since it is a function of the document object, it is invoked using the document object.

Var var_name=Object.getElementById(control_id);

The control_id is the argument that contains the ID of the control whose value has to be obtained for further processing. var_name is the name of the variable that stores the extracted value returned by the function.

Let’s illustrate the use of getElementById with a simple example code snipet.

 
<html>
<head><title>getElementById method Demo</title>
</head>
<body>
<script type="text/javascript">
function sample(){
 var val1 = document.getElementById('myid'); //get the value and store in val1
 if(val1 != "")
 alert("You typed this: " + val1.value)
 else
 alert("Please enter a text in the textbox")        
}
</script>
<input type='text' id='myid' />
<input type='button' onclick='sample()' value='Form Checker' />

</body>
</html>

The method getElementById looks very simple but has its own advantages and is a wonderful way to make dynamic interaction and updates.

Browse more tutorials...