Connecting JavaScript to HTML Buttons


When you run an Ajax application, you usually wait for the user to do something; you don’t simply execute your code when the page loads, as the examples in this chapter have done so far:

 <body onload="showMessage()">   <h1>Using the while loop</h1>   <div >   </div> </body>

To wait for the user to do something, you can wait for a browser event to happen. Events are commonly triggered by HTML controls, such as buttons, list boxes, text fields, checkboxes, and so on.

This example shows how to connect JavaScript code to a button. To create a button, you can use an HTML <input type="button"> element inside an HTML <form> element:

 <form>   <input type="button" value="Click Here"> </form>

How do you connect this button to a JavaScript function named, for example, showMessage? You do that with the onclick event handler:

 <form>   <input type="button" onclick="showMessage()"     value="Click Here"> </form>

That connects the button to the showMessage function, so when the user clicks the button, the showMessage function will be called. In the showMessage function, you can display a message, “You clicked the button,” in a <div> element like this in the Web page buttons.html:

 <html>     <head>         <title>Using buttons</title>         <script language="javascript">             function showMessage()             {               document.getElementById('targetDiv').innerHTML =              "You clicked the button.";             }         </script>     </head>     <body>         <h1>Using buttons</h1>         <form>           <input type="button" onclick="showMessage()"             value="Click Here">         </form>       <div >       </div>    </body> </html>

You can see what this page looks like in Figure 2.22.

image from book
Figure 2.22: A JavaScript-enabled button

When the user clicks the button, the browser calls the showMessage function, which displays the message, as you can see in Figure 2.23. All of which proves that the JavaScript showMessage function is indeed connected to the button.

image from book
Figure 2.23: Responding to a button click



Ajax Bible
Ajax Bible
ISBN: 0470102632
EAN: 2147483647
Year: 2004
Pages: 169

Similar book on Amazon
HTML, XHTML, and CSS Bible
HTML, XHTML, and CSS Bible
JavaScript Bible
JavaScript Bible
JavaScript Bible
JavaScript Bible
PHP and MySQL Web Development (4th Edition)
PHP and MySQL Web Development (4th Edition)

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net