![]() |
|
[Javascript] jQuery - Character counter TUT - Printable Version +- Hack Forums (https://hackforums.net) +-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444) +--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151) +---- Forum: Web Development (https://hackforums.net/forumdisplay.php?fid=183) +---- Thread: [Javascript] jQuery - Character counter TUT (/showthread.php?tid=3747184) |
jQuery - Character counter TUT - theAbsolute - Sep 10, 2013 This is a little script that will let you show your users how many characters can they type in the text area. So we will be now creating something like what can you see when composing a new tweet on the Twitter. Example: ![]() 1. HTML First, let's make a simple HTML page where we will put our input field for the users text. So, nothing hard, we will just create text area and our character counter label. Code <textarea id='commtext'></textarea>If you test it now, you'll see our text area there and "500 characters left" text below it. 2. jQuery Now we want to add some jQuery to it. First, we need to reference to the jQuery to make it work. Adding this to your HTML page Code <script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>Tip: Add jQuery above the closing body tag. (</body>) Just below the added jQuery, we are going to write our plugin. Let's look at it and I will explain it a bit: Code <script>As you can see, we have created a function which purpose is to count the typed characters. In it we have an IF ELSE statement for cases when there are 500 characters left (notice that 500 is our limit, so 500 is an empty text area) and less then 500 characters (else block). Else block is the key one, and it's not hard to see what it does. It's simply takes length (what is var len in our first line), and takes that from 500. In addtition I have added some css here to make the text red when all the 500 characters are typed. After IF ELSE statement we use KEYUP to detect the typing, and we parse that to our function. 3. We're done To put it together, your code should look like this: Code <!doctype html>* - [Rn] 7s^2 - Sep 22, 2013 Nice but a good approach to tutorial making is to go through each line to explain step by step and avoid using huge paragraphs... By that, newbie can understand it more properly. |