0

I am using the below code to set the character count on a textarea. This solution is working fine as far as i am passing the textarea ID.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" language="javascript" src="jquery.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        var charactersAllowed = 255; // this is picked from widget configuration
        $("#charCount").html(charactersAllowed);
        $("#message").keyup(function() {
            $("#charCount").html(charactersAllowed - ($(this).val().length));
            if($(this).val().length > charactersAllowed) {
                this.value = this.value.substring(0, charactersAllowed);
                $("#charCount").html(charactersAllowed - ($(this).val().length));
            }
        });
    });
</script>
</head>
<body>
    <textarea name="message" id="message" tabindex="4" rows="4" cols="35"></textarea>
    <p class="character_limit">Character limit: <span id="charCount"></span></p>
</body>
</html>

what i need to do is to wrap this functionality in function so that i can call this function on any input element. Can i wrap the same code inside a function name and call the same function on Textarea onchange() event?

Please provide me the inputs & help to recode this snippet.

Thanks Lokesh Yadav

3 Answers 3

1

You can apply what you have to any text area:

$(document).ready(function() {
    limitTextBox("#message", "#charCount", 255);
});

function limitTextBox(box, charsDisplay, charactersAllowed) {
    var $box = $(box),
        $charsDisplay = $(charsDisplay);
    $charsDisplay.html(charactersAllowed - ($box.val().length));
    $box.keyup(function() {
        $charsDisplay.html(charactersAllowed - ($box.val().length));
        if($box.val().length > charactersAllowed) {
            $box[0].value = $box[0].value.substring(0, charactersAllowed);
            $charsDisplay.html(charactersAllowed - ($box.val().length));
        }
    });

}

Live example

...but can I strongly recommend that you don't do that. Look instead at how StackOverflow limits input into text boxes (such as comments). They let you type whatever you want, but only actually let you save your comment if you're within range. This truncating the content as people type makes for a terrible user experience.

Off-topic: In your original function, sometimes you used val() on a jQuery instance, other times you used value on the raw DOM element. I've preserved that above, but you probably want to pick one or the other and use it throughout.

Sign up to request clarification or add additional context in comments.

2 Comments

very true T.J. But the thing is it's a client's requirement.
i will surely present your opinion to my manager to rethink on this implementation. your point makes sense in terms of user experience, thanks for responding so quickly :)
1

You could create a plugin like so:

(function($) {
   $.fn.charlimit = function(options) {
       var def = {limit: 250, display: null};
       $.extend(def, options);
       var $display = $(def.display);

       $display.html(def.limit);

       this.bind('change keyup', function() {
            var l = $(this).val().length;
            $display.html(def.limit - l);
            if(l > def.limit) {
                $(this).val(function(i, value) {
                     return value.substring(0, def.limit);
                });
                $display.html(def.limit - $(this).val().length);
            }
       });
       return this; 
   };   
}(jQuery));

And use it with:

$('#message').charlimit({limit: 250, display: '#charCount'});

DEMO

16 Comments

@Lokesh: You're welcome :) I'm not saying that this code is optimal though ;) One problem is that if you are applying the method on several elements (i.e. the selectors selects multiple elements), then they all share the same "display " element (which shows the character count). So either you apply this function only to single elements (one after another) or you somehow fix it to support multiple "display" elements.
i do not know if i made a mistake while incorporating your code.... whenever charcount become 0 then if i press any key again,.... charcount will go to -60 and showing function(i, value){} inside the textarea
@Lokesh: Mmh. I cannot reproduce this in my demo. Can you? If yes, then there is some error in the code. If not.... you made a mistake somewhere. Does the selector select one or multiple elements?
i placed only one textarea control on my page,
@Lokesh: You mean what I type into the text field? I just press random keys :D
|
0

Just use a class (in my example "myclass") on the textareas you want to check and modify this:

$("#message").keyup(function() { ...

Into this:

$("textarea.myclass").keyup(function() { ...

and

$("#charCount")

To

$(this).find('span.charCount')

Of course you have to edit your HTML and change the span ID to a class (thx @T.J. Crowder for pointing it out!)

4 Comments

Which does nothing whatsoever for all of the id-specific selectors inside his keyup function.
then i have to define classname on textarea. My question was like can i put onchange=sonefunction(this); on textarea and pass the reference to jquery function.
You really don't want to use that, trust me ;-) Don't mix your content, presentation and JS altogether. By calling the function on the right selector from your JS file, you separate things nicely. See en.wikipedia.org/wiki/Unobtrusive_JavaScript
this links contains so much useful information... thanks a lot Capsule :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.