HTML and CSS Reference
In-Depth Information
Listing 2-2.
HTML Markup of the Character Counter Form
<form id="form1" runat="server">
<span>Enter some text :</span>
<br />
<textarea id="textarea" rows="3" cols="50" class="TextArea"></textarea>
<br />
<span class="NormalCounter">Character counter : </span>
<span id="counter" class="NormalCounter"></span>
<br /><br />
<asp:Button ID="submit" runat="server" Text="Submit" OnClick="submit_Click" />
<br />
<asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
</form>
The Submit button and the associated message label are server controls. As usual, the CSS classes
used in the markup reside in a style-sheet file. Next, you need to write jQuery code that wires several event
handlers and makes the character counter functional. Listing 2-3 shows the
ready()
function that wires
event handlers for
keyup
,
blur
, and
click
events. The
keyup
and
blur
event handlers ensure that the
number of characters entered in the
textarea
are less than or equal to the maximum length. They also
update the character count in the corresponding
<span>
element.
Listing 2-3.
Event Wiring of the Character Counter
$(document).ready(function () {
var eventData = {
MaxLength: 20,
Type: 'Remaining',
AllowOverflow: true,
CounterId: 'counter',
NormalCss: 'NormalCounter',
WarningCss:'WarningCounter'
};
$("#textarea").keyup(eventData, OnKeyUp);
$("#textarea").blur(eventData,OnBlur);
$("#textarea").keyup();
$("#submit").click(function (event) {
if (!conirm("Do you wish to submit the form?")) {
event.preventDefault();
}
});
})
The
ready()
function is automatically called by jQuery when the entire HTML DOM tree is loaded in
the browser. You can pass your own function to the
ready()
function that wires event handlers for various
elements such as
textarea
and
<button>
. The code declares a variable (
eventData
) that stores configuration
settings you need to pass to the event handlers. Once the event handlers are wired, the
eventData
object is
automatically passed to the event handlers every time the event is raised. Notice that
eventData
is a JSON
object and takes the form of key-value pairs. A key and its value are separated by a colon (
:
) and multiple
key-value pairs are delimited by comma (
,
). Table 2-3 explains the purpose of each of the settings of the
eventData
object.