Delphinidin

Get any informations you need in depth explanation

Being able to limit a character count on an input field can be used to restrict how many words are included or how many characters you can include in your status message. The 140-character limit on Twitter (www.twitter.com) has made the limiting character count type of script quite popular in the past year, but it's still always a challenge to keep your message or thought under 140 characters. A character count limit can also display to the user how many characters they have left to work with under the limit.

1. The first step involves setting up the HTML. Set up an input field and give it an ID of status. This input is used with the change event to detect the characters being added.

<textarea cols="50" rows="5" id="status"></textarea>

2. Add an empty div called counter, which is where the remaining character number shows up as you type into the input field.

<div id="counter"></div>

3. Set up a variable called maxNum, which will be the maximum amount of characters allowed, and set it to 100.

var maxNum = 100;

4. Create a selector statement that will match the status element and bind the keypress event to the event handler. The keypress event fires each time a key on the keyboard is depressed and then released, which is the perfect event for testing input on form fields.

$('#status').bind({
keypress : function() {
});
});

5. After the keypress fires, you need to capture the value of the status input field. I have set up a variable called inputText that stores this value. Set up another variable called numChar, which stores the length of the inputText variable. Next, create a variable called charRemain, which holds the result of subtracting numChar from maxNum.

$('#status').bind({
keypress : function() {
var inputText = $(this).val();
var numChar = inputText.length;
var charRemain = numChar - maxNum;
});
});

6. After setting up all the variables, add a conditional statement using a comparison operator to check whether numChar is less than or equal to maxNum. If the expression returns true, select the counter element and change the text within to the variable charRemain, which is the number of remaining characters.

$('#status').bind({
keypress : function() {
var inputText = $(this).val();
var numChar = inputText.length;
var charRemain = numChar - maxNum;
if (numChar <= maxNum) {
$('.counter').text(charRemain);
}
}
});

7. Finally, add an else if statement that checks to see whether the maxNum is greater than or equal to the numChar. If this expression returns true, prevent the user from typing any more letters into the text field using event.preventDefault().

$('#status').bind({
keypress : function() {
var inputText = $(this).val();
var numChar = inputText.length;
var charRemain = numChar - maxNum;
if (numChar <= maxNum) {
$('.counter').text(charRemain);
}
else if (numChar > maxNum){
event.preventDefault();
}
});
});

0 comments:

Post a Comment

Site Info