innerHTML allows you to change parts of a web page dynamically. In my last tutorial about GET and POST in PHP, I showed how you could use a button and a textbox and then use GET or POST to print that text on the page. However, to do this, it refreshed the page. Using innerHTML, we will do it without refreshing the page. And, in another tutorial, I’ll be showing how to use ajax and innerHTML to be able to do things like pull information from a database and then use innerHTML to show it. But, on with this tutorial.
Firstly, we need to setup our page with a textbox and a normal button. I have explained some of this in previous tutorials, however, if you do not know how to set these bits up, I suggest you stop and go back over HTML. I have refrained from using a form element, simply because its not needed.
Now, we need to setup the spot where we will put our text. In our javascript code, we will be finding the spot by id, so we need to add an ID to an HTML tag. In this example, we will use a <p> tag with a id of namehere. We’ll also add an onclick event to our button, that will call a (yet to be made) javascript function.Code:<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"> <title></title> </head> <body> <input name="name" id="name"><br> <input name="Submit" value="Submit" type="button"> </body> </html>
Now, we need to implement the javascript function. In this function we set the innerHTML property of the namehere id element to “Hello, “ and then add on the value of the name textbox.Code:<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"> <title></title> </head> <body> <p id="namehere"></p> <input name="name" id="name"><br> <input name="Submit" value="Submit" onclick="javascript:changename()" type="button"></body> </html>
Run the page, and you’ll find that once you enter a name and press submit, the words “Hello, Whatevernnameyouputin” just above the textbox. I will have a live demo up on my codecall subdomain shortly.Code:<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"> <title></title> </head> <body> <script type="text/javascript">function changename() { document.getElementById('namehere').innerHTML = "Hello, " + document.getElementById('name').value; } </script> <p id="namehere"></p> <input name="name" id="name"><br> <input name="Submit" value="Submit" onclick="javascript:changename()" type="button"></body> </html>
If this tutorial was helpful, please +rep me![]()


LinkBack URL
About LinkBacks





Reply With Quote




im a code-warrior, see my avatar



Bookmarks
Algorithms and Data Structures
Java tutorials
Algorithms Forum