Javascript getElementByID

The document.getElementById() method returns the element of specified id.

In below example we receive input field by using document.getElementById() method, here document.getElementById() receive input value on the basis of input field id.

Example

<!DOCTYPE html>  
<html>  
<body>  
<head>  
<script type="text/javascript">  
function squre()  
{    
var num=document.getElementById("number").value;    
alert(num*num);    
}    
</script>  
</head>  
<form>  
Enter No:<input type="text" id="number" name="number"/><br/>  
<input type="button" value="squre" onclick="squre()"/>  
</form>  
</body>  
</html>

Code Explanation

varnum=document.getElementById("number").value; In this code getElementById value from input field which have Id number.

Example

<!DOCTYPE html>  
<html>  
<body>  
<head>  
<script type="text/javascript">  
function squre()  
{    
var num=document.getElementById("number").value;    
var result=num*num;    
document.getElementById("answer").value=result;  
}     
</script>  
</head>  
<form>  
Enter No:<input type="text" id="number" name="number"/>  
<input type="button" value="squre" onclick="squre()"/>  
<input id="answer"/>  
</form>  
</body>  
</html>



ADVERTISEMENT
ADVERTISEMENT