JavaScript getElementById

Accessing Form Elements using getElementById

In order to access the form element, we can use the method getElementById() like this:

var name_element = document.getElementById(‘txt_name’);

Here txt_name is id of any form fields.

Consider this form input element,

<input type=”text” name=”name” id=”txt_name” value=”learn web development”>

Do you know how to get this value using javascript? See below example

<script type=”text/javascript”>
function getformvalue()
{
var name_element = document.getElementById(‘txt_name’);
alert(name_element.value);
}
</script>
<input type=”text” name=”name” id=”txt_name” value=”learn web development”>
<input type=”button” value=”Get this value” onClick=”getformvalue();”>

When you click ‘Get this value’ button it just show ‘learn web development’ with alert box.

Display:


When using the getElementById function, you need to remember a few things:

getElementById is a method (or function) of the document object. So you can only access it by using document.getElementById.

Also, be sure that you set your HTML elements’ id attributes if you want to use this function. Without an id, you could not get value of form fields. In this case it does not return anything; it shows error only like ‘name_element is null’.  If you want to see this error – for firefox go to Tools->Error console (tools menu in browser), for IE it shows error in status bar.

Posted in Javascript Tagged with: