Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 25
  1. #1
    Regular Coder
    Join Date
    Oct 2011
    Posts
    106
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Character Limiter

    A character limiter/counter that manages to do it all in just 28 lines of Javascript/JQuery and 2 pertinent lines of HTML


    The JQuery/Javascript
    Code:
    $(document).ready(function(){
        var hi = 200;
        var cu = 0;
        $("#rem").html(eval(hi - cu));
        $("#in").keyup(function(){
        	var cu = $(this).val().length;
    	$("#rem").html(eval(hi - cu));
        	if(eval(hi - cu) < 0){
    	    while(eval(hi - cu) < 0){
    		$(this).val( $(this).val().replace(/(\s+)?.$/, "") );
    		cu = cu - 1;
    		$("#rem").html(eval(hi - cu));
    	    }
    	}
        });
    });
    The HTML
    Code:
    <!DOCTYPE html>
    <html>
        <body>
            <textarea id="in"></textarea><br>
            <span>Characters Remaining: </span><span id="rem"></span>
        </body>
    </html>
    Edit the var hi = 200; to change the character limit.

  • #2
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,459
    Thanks
    0
    Thanked 632 Times in 622 Posts
    You don't need jQuery or eval to do that in far less c ode than you have there.

    Just another example of someone using jQuery to do something that can be done in fewer lines of ordinary JavaScript.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #3
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,026
    Thanks
    36
    Thanked 494 Times in 488 Posts

    Lightbulb

    Six lines of a function with your two lines of HTML.
    No jquery and no eval() usage.
    Code:
    <html>
    <head>
    <title> Untitled </title>
    <script type="text/javascript">
    // From: http://www.codingforums.com/showthread.php?t=257717
    
    function ckTxtLen() {
      var charLimit = 200;
      var sel = document.getElementById('txtIn').value.length;
      document.getElementById('txtRemain').innerHTML = charLimit-sel;
      return true;
    }
    </script>
    
    <style type="text/css">
    
    </style>
    </head>
    <body>
      <textarea id="txtIn" onkeypress="ckTxtLen()" maxlength="200"></textarea>
      <div>Characters Remaining: <span id="txtRemain"></span></div>
    </body>
    </html>
    You could also change a bit to make it so multiple <textarea>s could be used.


    Like this:
    Code:
    <html>
    <head>
    <title> Limit Textarea Input </title>
    <script type="text/javascript">
    // From: http://www.codingforums.com/showthread.php?t=257717
    
    function ckTxtLen(IDS) {
      var obj = document.getElementById(IDS);
      document.getElementById(IDS+'Remain').innerHTML
        = obj.getAttribute('maxlength') - obj.value.length;;
      return true;
    }
    </script>
    
    <style type="text/css">
    
    </style>
    </head>
    <body>
      <textarea id="txtIn0" onkeypress="ckTxtLen(this.id)" maxlength="200"></textarea>
      <div>Chars. Remaining: <span id="txtIn0Remain">200</span></div>
      <textarea id="txtIn1" onkeypress="ckTxtLen(this.id)" maxlength="100"></textarea>
      <div>Chars. Remaining: <span id="txtIn1Remain">100</span></div>
      <textarea id="txtIn2" onkeypress="ckTxtLen(this.id)" maxlength="50"></textarea>
      <div>Chars. Remaining: <span id="txtIn2Remain">50</span></div>
    </body>
    </html>
    Last edited by jmrker; 04-18-2012 at 04:23 PM.

  • #4
    The fat guy next door VIPStephan's Avatar
    Join Date
    Jan 2006
    Location
    Halle (Saale), Germany
    Posts
    8,474
    Thanks
    6
    Thanked 980 Times in 953 Posts
    Quote Originally Posted by jmrker View Post
    You da man!




  • #5
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,730
    Thanks
    202
    Thanked 2,508 Times in 2,486 Posts
    Slight snag. The user can paste into the textarea, and if he pastes in 300 characters the remaining count shows -100.

    Here is my proposal:-

    Code:
    <html>
    <head>
    
    <script type = "text/javascript">
    
    var maxLen = 400; // max number of characters allowed  // global variable
    var max = "You may enter up to " + maxLen + " characters";  // global variable
    
    function OnPaste () {
    //return false;   // cancels (blocks)  the onpaste event.  Uncomment this line to block pasting
    setTimeout(checkMaxInput,100);  // delay is necessary
    }
    
    function initCount() {
    document.getElementById("limit").innerHTML = max; 
    document.getElementById("remLen").value = maxLen;
    }
    
    function checkMaxInput() {
    var form = document.myform;  // or document.forms[0] or document.getElementById("myform");
    if (form.txtarea.value.length > maxLen) {   // if too long.... trim it!
    form.txtarea.value = form.txtarea.value.substring(0, maxLen);
    document.getElementById("message").innerHTML = "Too many characters were entered!!  The excess over " + maxLen + " have been removed.";
    }
    else {
    document.getElementById("message").innerHTML = "";
    }
    form.remLen.value = maxLen - form.txtarea.value.length;
    }
    
    </script>
    
    </head>
    
    <body onload = "initCount()">
    
    <form name = "myform" id = "myform">
    <span id = "limit"  style="font-size: 10pt;color: #FF0000;font-family: arial, helvetica, sans-serif;"></span>
    <br>
    <textarea name="txtarea" wrap=physical cols=48 rows=10  onkeyup="checkMaxInput()"  onblur="checkMaxInput()" onpaste="OnPaste ()" >
    </textarea>
    <br>
    <input readonly type=text name=remLen id = "remLen" size=3 value = ""> characters left</font>
    </form>
    <span id = "message" style="color:red";></span>
    </body>
    </html>
    Last edited by Philip M; 04-19-2012 at 06:05 PM. Reason: Change limit to 400 chars

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #6
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,184
    Thanks
    10
    Thanked 569 Times in 550 Posts
    A character limiter/counter that manages to do it all in just 0 lines of Javascript/JQuery and 1 pertinent line of HTML:

    Code:
    <textarea maxlength="50"></textarea>
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/1/19) IE7:0.2, IE8:6.7, IE11:7.4, IE9:3.8, IE10:4.4, FF:18.3, CH:43.6, SF:7.8, MOBILE:27.5

  • #7
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,459
    Thanks
    0
    Thanked 632 Times in 622 Posts
    Quote Originally Posted by rnd me View Post
    A character limiter/counter that manages to do it all in just 0 lines of Javascript/JQuery and 1 pertinent line of HTML:

    Code:
    <textarea maxlength="50"></textarea>
    maxlength is only valid on input fields - you can't use it on textarea fields as there is no such attribute on that field type.

    The only way to limit textarea content client side is using JavaScript.

    A version of this that I wrote many years ago can be found at http://www.felgall.com/jstip20.htm - that doesn't display the number of characters remaining though - athough adding it would only require one extra statement.
    Last edited by felgall; 04-19-2012 at 10:13 PM.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #8
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,184
    Thanks
    10
    Thanked 569 Times in 550 Posts
    Quote Originally Posted by felgall View Post
    maxlength is only valid on input fields - you can't use it on textarea fields as there is no such attribute on that field type.
    worked for me when i tried it. the textarea objects i looked at even have a "maxLength" dom binding... If nothing else, it's a good way to take care of a lot of visitors without js. It's also perfect to hold the length setting next to the other validation settings of the textarea like @required and @pattern, unlike Philip M's example when the validation restriction is not simply determinable by using "inspect element" on the textarea, and requires global variables that limit the checker's re-use.

    see http://www.w3schools.com/html5/att_t..._maxlength.asp for specifics.

    edit:
    i see it does not work in ie9, but does on 10.
    Last edited by rnd me; 04-21-2012 at 09:10 PM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/1/19) IE7:0.2, IE8:6.7, IE11:7.4, IE9:3.8, IE10:4.4, FF:18.3, CH:43.6, SF:7.8, MOBILE:27.5

  • #9
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,459
    Thanks
    0
    Thanked 632 Times in 622 Posts
    Quote Originally Posted by rnd me View Post
    worked for me when i tried it. the textarea objects i looked at even have a "maxLength" dom binding... If nothing else, it's a good way to take care of a lot of visitors without js. It's also perfect to hold the length setting next to the other validation settings of the textarea like @required and @pattern,
    So it must be one of the useful attributes that HTML 5 is adding - like pattern is a useful addition and unlike required which is not a useful addition because the addition of pattern makes required completely unnecessary.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #10
    Regular Coder
    Join Date
    Dec 2010
    Location
    Sheffield, UK
    Posts
    138
    Thanks
    81
    Thanked 1 Time in 1 Post
    So, basically, the conclusion of this thread is that JS, or any script for that matter, is not needed to limit the amount of characters a user can enter in a text field, because it can be accomplished with a single HTML attribute? Is this correct? Or am I getting the wrong end of the stick?
    http://www.topcashback.co.uk/ref/hashim1

    ^
    Total earnings so far: 25.15
    A very generous cashback site worth checking out.


  • #11
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,459
    Thanks
    0
    Thanked 632 Times in 622 Posts
    Quote Originally Posted by Hashim1 View Post
    So, basically, the conclusion of this thread is that JS, or any script for that matter, is not needed to limit the amount of characters a user can enter in a text field, because it can be accomplished with a single HTML attribute? Is this correct? Or am I getting the wrong end of the stick?
    It appears that the necessary attribute has been added to the textarea tag in HTML 5 so you'd only need to use JavaScript for browsers that haven't implemented that useful proposal yet. The attribute has always been available on input tags.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #12
    Regular Coder
    Join Date
    Dec 2010
    Location
    Sheffield, UK
    Posts
    138
    Thanks
    81
    Thanked 1 Time in 1 Post
    Quote Originally Posted by felgall View Post
    It appears that the necessary attribute has been added to the textarea tag in HTML 5 so you'd only need to use JavaScript for browsers that haven't implemented that useful proposal yet. The attribute has always been available on input tags.
    Is there anyway of finding which have and which haven't?
    http://www.topcashback.co.uk/ref/hashim1

    ^
    Total earnings so far: 25.15
    A very generous cashback site worth checking out.


  • #13
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,459
    Thanks
    0
    Thanked 632 Times in 622 Posts
    Quote Originally Posted by Hashim1 View Post
    Is there anyway of finding which have and which haven't?
    Not really since browsers only implement it to allow testing at the moment as HTML 5 is still only a proposal.

    If you add the attribute in the HTML then you could add a couple of lines of JavaScript that grab the attribute and perform the check using that value and then it wouldn't make any difference whether the browser supports the attribute directly or not.

    possibly the following (since maxlength generally just discards what doesn't fit there would be no need for an error message):

    Code:
    <textarea rows="5" cols="50" maxlength="500"
    onkeyup="if (this.value.length > this.maxlength) this.value = this.value.substring(0, this.maxlength)">
    Last edited by felgall; 04-29-2012 at 12:03 AM.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • Users who have thanked felgall for this post:

    Hashim1 (04-30-2012)

  • #14
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,355
    Thanks
    11
    Thanked 558 Times in 551 Posts
    The limit can be accomplished by using the maxlength attribute only. But if you want to count the remaining characters you'll need to do some scripting.

  • Users who have thanked devnull69 for this post:

    Peeyush (04-30-2012)

  • #15
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,730
    Thanks
    202
    Thanked 2,508 Times in 2,486 Posts
    Quote Originally Posted by Hashim1 View Post
    So, basically, the conclusion of this thread is that JS, or any script for that matter, is not needed to limit the amount of characters a user can enter in a text field, because it can be accomplished with a single HTML attribute? Is this correct? Or am I getting the wrong end of the stick
    Textbox - yes
    Textarea - no (in HTML4)
    Last edited by VIPStephan; 04-29-2012 at 07:09 PM. Reason: changed quote author

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • Users who have thanked Philip M for this post:

    Hashim1 (04-30-2012)


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •