JavaScripTools Manual
InputMask
Working with the SizeLimit
A classic problem in web applications is to limit the number of characters on a textarea.
Many use something like onkeyup="if (this.value.length > 500) this.value = this.value.substring(0, 500)"
.
That's ugly.
SizeLimit is used just like all other masks, and handles both onkeyup and onblur events (many
people forget that the user can paste data with mouse). Aditionally, it can display a custom text on a given
html element or input field, or allow the user to perform custom actions. Look at the
samples to see what SizeLimit can do.
The contructor arguments are (only the first two are mandatory):
- control: The control name or reference. Mandatory
- maxLength: The maximum value length. Mandatory
- output: A control or html element name or reference, where the outputText will be displayed. Optional.
- outputText: A text that will be displayed on the output control. The default value is defined by the constant
JST_DEFAULT_LIMIT_OUTPUT_TEXT (check here for details about default value
customization). You can use the following variables:
- ${size}: Replaced by the current text size
- ${left}: Replaced by the number of characters left
- ${max}: Replaced by the maximum of characters that the control accepts
Note: If you are setting those variables in a JSP 2.0 page you would have to escape them, or
they would be interpreted as a server-side scoped variable. In that case, you can use \${size}, for example.
The same may happen with other template processors that interprets ${...} as variable holders.
- The others, updateFunction, keyUpFunction, blurFunction, are event handlers and are not recommended
to pass on the contructor, but as properties. For more information about custom event handlers, check the
introduction. Important: Unlike the other masks, the updateFunction
does not receive the SizeLimit instance, but the following arguments: The control instance, size the current size,
the maximum size and the characters left. But, remember that it is evaluated by the SizeLimit instance, so, this
refers to the SizeLimit itself.
Here are some examples (assuming a textarea named "text" and a div named "text_output"):
//The simplest way
new SizeLimit("text", 500);
//Using an output
var limit = new SizeLimit("text", 500);
limit.output = "text_output";
limit.outputText = "${size}/${max}" //This would display sometihing like "127/500"
//Using a custom function to display the percent left
function onUpdate(control, size, max, left) {
setValue("text_output", Math.round(size * 100 / max) + "%");
}
var limit = new SizeLimit("text", 500);
limit.updateFunction = onUpdate;