Task 1 — Form event handlers: onClick & onSubmit
HTML tags are represented in JavaScript as objects and tag attributes as properties. Accessing an element's value by its name is the get element by name technique; using getElementById() is the get element by ID technique.
- Type a value into each field and click the buttons.
- Notice the first form uses
onclick, the second usesonsubmit.
Code
<h1>Form Event Handlers</h1>
<form name="myform1">
<label>Value x: <input type="text" name="x"></label>
<input type="button" value="Display X" onclick="DisplayX()">
</form>
<form name="myform2" onsubmit="return DisplayY();">
<label>Value y: <input type="text" id="y"></label>
<input type="submit" value="Submit">
</form>
// Get element by name
function DisplayX() {
alert(document.myform1.x.value);
}
// Get element by ID
function DisplayY() {
var thisY = document.getElementById("y");
alert(thisY.value);
return false; // prevent the form from submitting
}