Changing the innerHTML

Popping up windows is not considered a good way of user interaction. Often is better to think of another way, less intrusive, to communicate.

With JavaScript we can modify the text in a HTML element, changing in this way the actual page, changing the content of its innerHTML property.

Let's use this capability to improve the input text validation example.

We change the HTML adding a "span" element, initially empty, just after our text input.
We change the validation function, too, to accept in input both the text input and the related span element:

<form name="order" action="notImplemented" method="POST">
<p>Your input:
<input id="msgId" name="message" type="text" size="40"
onblur="basicCheck(this, document.getElementById('msgHlp'))" />
<i><span id="msgHlp"></span></i></p>
<input type="button" value="Do it" onclick="doSomething(this.form);" />
</form>

The idea is that we are going to put a message in the "span" element, if the text input is not valid.

We change the validation function in this way:

function basicCheck(fldInput, fldHelp) {
if(fldInput.value.length == 0) {
if(fldHelp != null)
fldHelp.innerHTML = "Please enter a value";
fldInput.focus();
}
else {
// ensure no help message is showed when not required
if(fldHelp != null)
fldHelp.innerHTML = "";
}
}

If a fldHelp is specified, and if the string in fldInput is empty, the fldHelp text is set to a helper text.

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

No comments:

Post a Comment