Main Page

formatEvent

TextUtil.blockChars = function (oTextbox, oEvent, bBlockPaste) {
oEvent = EventUtil.formatEvent(oEvent);
var sInvalidChars = oTextbox.getAttribute(“invalidchars”);
var sChar = String.fromCharCode(oEvent.charCode);
var bIsValidChar = sInvalidChars.indexOf(sChar) == -1;
if (bBlockPaste) {
return bIsValidChar && !(oEvent.ctrlKey && sChar == “v”);
} else {
return bIsValidChar || oEvent.ctrlKey;
}
};
TextUtil.allowChars = function (oTextbox, oEvent, bBlockPaste) {
oEvent = EventUtil.formatEvent(oEvent);
var sValidChars = oTextbox.getAttribute(“validchars”);
var sChar = String.fromCharCode(oEvent.charCode);
var bIsValidChar = sValidChars.indexOf(sChar) > -1;
if (bBlockPaste) {
return bIsValidChar && !(oEvent.ctrlKey && sChar == “v”);
} else {
return bIsValidChar || oEvent.ctrlKey;
}
};
Notice that the same code is added to both methods. First, a third argument is added,
bBlockPaste
,
which must be set to
true
if you want to block pasting in a text box. Then, an
if
statement is added at
the end of each method, to check whether pasting should be blocked. If so, the return value is
true
only
if the character is valid and Ctrl + V hasn’t been pressed. If pasting shouldn’t be blocked, the
return
statement from the original method is used.
To use the new methods, just add the third argument:
<input type=”text” validchars=”0123456789”
onpaste=”return false” oncontextmenu=”return false”
onkeypress=”return TextUtil.allowChars(this, event, true)” />
<textarea rows=”10” cols=”25” validchars=”0123456789”
onpaste=”return false” oncontextmenu=”return false”
onkeypress=”return TextUtil.allowChars(this, event, true)” />
Even though the third argument is defined, you can still use these methods with only the first two argu-
ments, because an
undefined
value is considered
false
when used in the
if
statement and won’t
block pasting.
352
Chapter 11
14_579088 ch11.qxd 3/28/05 11:40 AM Page 352


JavaScript EditorFree JavaScript Editor     Ajax Editor


©