For this example we'll use the document object model to check a checkbox.
Key Points
Name the form (in this first example, we named the form Example1. You do this so you can use dot notation to refer to "theForm.theField.value".
Text objects have value property you can use to check.
You can add an onClick JavaScript event to the form. In this case, we used the event to call a function.
Here's the function code :
function CheckFieldBlank() {
if (Example1.Field1.value == ""){
alert("It's Blank!");
} else { alert("It's not blank.");
};
Here's the form code:
<form method="Post" name="Example1">
<input type="text" name="Field1" size="20">
<input type="button" value="Check If Blank"
onclick="CheckFieldBlank();">
</form>
Checking if a field has a specific value
One more example. This example show how to check for a specific value. In this case we check for the value 'Mike' in the field.
Here's the function:
function CheckFieldMike() {
if (Example2.Field1.value == "Mike"){
alert("It's Mike!");
} else { alert("It's not Mike.");
};
Here's the form code:
<form method="Post" name="Example2">
<input type="text" name="Field1" size="20">
<input type="button"
value="Check If Blank" onclick="CheckFieldMike();">
</form>
Here's the working sample:
[Load Demo] - Remember, you can view the source of browser-side JavaScript.
What's Next
Now that you know how to add JavaScript to your HTML pages and a bit about the JavaScript event model, it's time to explore the various capabilities of JavaScript. Try adding a few scripts to your HTML pages fromt his website. As you do, study in detail each script you add to your pages.