Java Reference
In-Depth Information
The type attribute is set to button , and the value attribute is set to the text you want to appear on
the face of the button. You can leave the value attribute off, but you'll end up with a blank button,
which will leave your users guessing as to its purpose.
This element creates an associated HTMLInputElement object (in fact, all <input/> elements
create HTMLInputElement objects); in this example it is called myButton . This object has all
the common properties and methods described earlier, including the value property. This
property enables you to change the text on the button face using JavaScript, though this is
probably not something you'll need to do very often. What the button is really all about is the
click event.
You connect to the button's click event just as you would with any other element. All you need to
do is define a function that you want to execute when the button is clicked (say, buttonClick() ) and
then register a click event listener with the addEventListener() method.
Counting Button Clicks
trY it out
In the following example, you use the methods described previously to record how often a button has
been clicked.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 11: Example 2</title>
</head>
<body>
<form action="" name="form1">
<input type="button" name="myButton" value="Button clicked 0 times" />
</form>
<script>
var myButton = document.form1.myButton;
var numberOfClicks = 0;
function myButtonClick() {
numberOfClicks++;
myButton.value = "Button clicked " + numberOfClicks + " times";
}
myButton.addEventListener("click", myButtonClick);
</script>
</body>
</html>
Save this page as ch11 _ example2.html . If you load this page into your browser, you will see a button
with “Button clicked 0 times” on it. If you repeatedly press this button, you will see the number of
button clicks recorded on the text of the button.
You start the script block by defining two variables called myButton and numberOfClicks . The former
holds a reference to the <input/> element object. You record the number of times the button has been
clicked in the latter and use this information to update the button's text.
Search WWH ::




Custom Search