18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 11<br />

To use this method, insert it into the HTML code for a text box (either or ) along<br />

with the invalidchars attribute:<br />

<br />

<br />

This one function can be used to block characters in a variety of useful ways:<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

<br />

Allowing valid characters<br />

Naturally, the other method of restricting user input is to only allow certain characters in a text box.<br />

Once again, the easiest way to accomplish this is to add an HTML attribute to a text box:<br />

<br />

This example would allow the numbers 0 through 9 only, and no other characters. Naturally, you’ll need<br />

to have an allowChars() method that does the opposite of the blockChars() method:<br />

TextUtil.allowChars = function (oTextbox, oEvent) {<br />

oEvent = EventUtil.formatEvent(oEvent);<br />

var sValidChars = oTextbox.getAttribute(“validchars”);<br />

var sChar = String.fromCharCode(oEvent.charCode);<br />

var bIsValidChar = sValidChars.indexOf(sChar) > -1;<br />

};<br />

return bIsValidChar || oEvent.ctrlKey;<br />

As you can see, the allowChars() has a lot in common with blockChars(): It accepts the text box and<br />

the event object as arguments; it formats the event object using EventUtil.formatEvent(); it stores<br />

the character that will be entered into the text box in a variable using String.fromCharCode(). The<br />

350

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!