HTML and CSS Reference
In-Depth Information
Notice how
event.target.id
is used to retrieve the ID of
<textarea>
and
event.data.CounterId
is used
to retrieve the ID of
<span>
. These IDs are stored in two variables (
id
and
counterid
) for later use. The
val()
method returns the text entered in the
<textarea>
and is stored in another local variable (
text
). Depending
on the type of counter (
Remaining
or
Total
), the code checks the length of the text data entered in the
<textarea>
against the
MaxLength
value. If
Type
is
Remaining
, the check is performed as follows:
diff = event.data.MaxLength - $(id).val().length;
if (diff < 0) {
$(counterid).removeClass(event.data.NormalCss);
$(counterid).addClass(event.data.WarningCss);
}
else {
$(counterid).removeClass(event.data.WarningCss);
$(counterid).addClass(event.data.NormalCss);
}
If the difference between the length of the text and
MaxLength
is less than 0, it indicates that the text
has exceeded its maximum allowed length. In that case, you should display the counter with the
WarningCss
class. To do this, you first remove the
NormalCss
class using the
removeClass()
method and then
apply the
WarningCss
class using the
addClass()
method. If the difference is greater than 0, you should
apply the
NormalCss
class by removing the
WarningCss
class.
If the counter
Type
is
Total
, the CSS classes are applied as shown here:
diff = $(id).val().length;
if (diff > event.data.MaxLength) {
$(counterid).removeClass(event.data.NormalCss);
$(counterid).addClass(event.data.WarningCss);
}
else {
$(counterid).removeClass(event.data.WarningCss);
$(counterid).addClass(event.data.NormalCss);
}
If the length of the text entered is more than the
MaxLength
value, the
NormalCss
class is removed using
the
removeCss()
method and the
WarningCss
class is applied using
addClass()
. Otherwise,
WarningCss
is
removed and
NormalCss
is applied.
Finally, after the code performs the length checking based on the
Type
setting, the counter value is
assigned to the
<span>
element using the
text()
method.
If the
AllowOverflow
setting is
false
, further text entered by the user is trimmed to the value of
MaxLength
using the
substring()
JavaScript function. The trimmed text is assigned to the
<textarea>
using
the
text()
method.
The
OnBlur
() event-handler function is shown in Listing 2-5.
Listing 2-5.
Handling the
blur
Event
function OnBlur(event) {
var id = "#" + event.target.id;
$(id).keyup();
}
The
OnBlur()
event-handler function simply triggers the
keyup
event programmatically. This way, even
if the user enters text in the
<textarea>
using a copy-paste technique (Ctrl+V or a shortcut menu), the
counter still reflects the correct value when the user exits the
<textarea>
.