Tutorial - Javascript - Add two numbers |
|
| Author | Ian - Tutorial Posts = 62 |
| This tutorial demonstrates how to get two inputs from the user within a HTML page and have a button on the page to call a javascript method to process the inputs and alter the answer output on the web-page. Within HTML, there are input tags that allow the user to input data that is passed either to a javascript method to validate the inputs (for example a registration forum) or to pass data back to the server (after the validation has taken place if required). The value 1 input is defined as value 1 = <input type=”text” id=value1” name=”value1” value=”1”/> the input type is text, which means any textual value, [A-Z]*[0-9]* but in this case since just adding integers [0-9] would be the required input. The id is for getting the value from the input with using javascript document.getElementById, value is for setting the default value. The function within the javascript, addNumbers() will get the inserted value1 by using the javascript document object. Within this object there is a method called getElementById that returns back the object, which in turn using the .value of the object returned can be passed to the parseInt (which converts a string value into a integer value). The same method is used for the answer input within the web-page (getElementById) but assign the return object to a variable allows access to the .value to set the value on the web-page. The source code is --- <html> <head> <title>Input tutorial</title> <script language="javascript"> function addNumbers() { var val1 = parseInt(document.getElementById("value1").value); var val2 = parseInt(document.getElementById("value2").value); var ansD = document.getElementById("answer"); ansD.value = val1 + val2; } </script> </head> <body> value1 = <input type="text" id="value1" name="value1" value="1"/> value2 = <input type="text" id="value2" name="value2" value="2"/> <input type="button" name="Sumbit" value="Click here" onclick="javascript:addNumbers()"/> Answer = <input type="text" id="answer" name="answer" value=""/> </body> </html> --- save as addtwonumbers.html and then open in a web browser (e.g. FireFox) |
|
| Copyright@CodingFriends, 2005-2006. All Rights Reserved. | |
| Home | Forums | Tutorials | Users | |
