Pages

Validation: accessing a field in a form

We want to ensure that a text input we put in a HTML form is not empty. To do that we have to associate a function to the event handler onblur (meaning: we are leaving the element), and we should pass the element itself to the checking function.

We have a really this simple form:

<form name="order" action="notImplemented" method="POST">
<input id="msgId" name="message" type="text" size="40" onblur="basicCheck(this)" />
<input type="button" value="Do it" onclick="doSomething(this.form);" />
</form>

When we leave the text input, an onblur event is generated, and so the function basicCheck() is called.
The parameter "this" is a reference to the element that was in control, so, the text input itself.

Here is how we check the text input value:

function basicCheck(inputField) {
if(inputField.value.length == 0) {
alert("Please enter a value");
inputField.focus();
}
}

In the parameter inputField we have the "this" referring to the text input. In its "value" property we have the string input by the user. In "length" is stored is actual length, so we check it against zero.

In case of empty text, we issue an alert, reset the focus on the "bad" input, and return the control to the user.

As a bonus, in this post we have a look to the onclick for the button in our minimal form. A function is called passing the form associated with the button itself, meaning, the form that contains the button (and incidentally, the text input too).

The idea is that in this way we have an easy access to the element in the form from the function:

function doSomething(form) {
alert("You wanted to do something with: " + form["message"].value);
alert("But you can't do anything here with: " + form.message.value);
}

Not a big function, but it shows us how we can access the elements in a form. We can use the array notation, (form["message"].value), or the "dot" notation, form.message.value, for getting absolutely the same result.

More details on this stuff in chapter seven of Head First JavaScript.

No comments:

Post a Comment