Bookmark and Share

JavaScript getElementById

Have you ever tried to use JavaScript to do some form validation? Did you have any trouble using JavaScript to grab the value of your text field? There's an easy way to access any HTML element, and it's through the use of id attributes and the getElementById function.

Advertise on Tizag.com

JavaScript document.getElementById

If you want to quickly access the value of an HTML input give it an id to make your life a lot easier. This small script below will check to see if there is any text in the text field "myText". The argument that getElementById requires is the id of the HTML element you wish to utilize.

JavaScript Code:

<script type="text/javascript">
function notEmpty(){
	var myTextField = document.getElementById('myText');
	if(myTextField.value != "")
		alert("You entered: " + myTextField.value)
	else
		alert("Would you please enter some text?")		
}
</script>
<input type='text' id='myText' />
<input type='button' onclick='notEmpty()' value='Form Checker' />

Display:

document.getElementById returned a reference to our HTML element myText. We stored this reference into a variable, myTextField, and then used the value property that all input elements have to use to grab the value the user enters.

There are other ways to accomplish what the above script does, but this is definitely a straight-forward and browser-compatible approach.

Things to Remember About getElementById

When using the getElementById function, you need to remember a few things to ensure that everything goes smoothly. You always need to remember that getElementById is a method (or function) of the document object. This means you can only access it by using document.getElementById.

Also, be sure that you set your HTML elements' id attributes if you want to be able to use this function. Without an id, you'll be dead in the water.

If you want to access the text within a non-input HTML element, then you are going to have to use the innerHTML property instead of value. The next lesson goes into more detail about the uses of innerHTML.

Bookmark and Share




Found Something Wrong in this Lesson?

Report a Bug or Comment on This Lesson - Your input is what keeps Tizag improving with time!

Advertise Here

More Tutorials!
Microsoft Office Tutorials Artist Tutorials