4

On the page there are number of text area. The number is dynamic not fixed. I need to limit length of all text areas on one page. How can I do this in js or jquery?


My try:-

<body>
        <div id="contact">
            <form action="" method="post">
                <fieldset>
                    <table style="width: 100%;">
                        <tr class="questionsView" style="width: 100%;margin: 5px;">
                            <td class="mandatory">
                                <b>1&nbsp;
                                    *Qywerew we</b>
                                <hr/>
                                <table class="profileTable" style="margin-left: 25px;">
                                    <tr>
                                        <td>
                                            <textarea style="border: solid 1px #800000;" rows="5" name="165" cols="100">
                                            </textarea>
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                &nbsp;
                            </td>
                        </tr>
                        <tr class="questionsView" style="width: 100%;margin: 5px;">
                            <td class="">
                                <b>2&nbsp;
                                    a da da da</b>
                                <hr/>
                                <table class="profileTable" style="margin-left: 25px;">
                                    <tr>
                                        <td>
                                            <textarea style="border: solid 1px #800000;" rows="5" name="166" cols="100">
                                            </textarea>
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                        <tr>
                            <td>
                                &nbsp;
                            </td>
                        </tr>
                    </table>
                    <input type="submit" value="Submit" onclick="return checkThis()">
                </fieldset>
            </form>
        </div>
        <script>
            $('textarea').bind('paste keyup blur', function(){
                $(this).val(function(i, val){
                    return val.substr(0, 5);
                });
            });
        </script>
    </body>
Harry Joy
  • 58,650
  • 30
  • 162
  • 207
  • I've recently had the same task and couldn't find anything reliable across all browsers. Specifically, I had a problem of pasting the text using the right-click context menu. – Kobi Aug 23 '11 at 04:32
  • 1
    possible duplicate of [How to impose maxlength on textArea in HTML using JavaScript](http://stackoverflow.com/questions/1125482/how-to-impose-maxlength-on-textarea-in-html-using-javascript) – jfriend00 Aug 23 '11 at 04:35

3 Answers3

3
$('textarea').bind('paste keyup blur', function() {
    $(this).val(function(i, val) {
        return val.substr(0, 5);
    });
});

jsFiddle.

Update

I don't know why but it prints function(i, val) { return val.substr(0, 5); } in text area every time.

Sounds like you are using an older version of jQuery (pre 1.4). The refactored code below will work.

$('textarea').bind('paste keyup blur', function() {
    $(this).val(this.value.substr(0, 5));
});

jsFiddle.

The previous code would not work prior to jQuery 1.4 because it expected a string only as the argument to val(). By passing a function, its toString() was implicitly called, returning the string representation of the function.

Community
  • 1
  • 1
alex
  • 479,566
  • 201
  • 878
  • 984
  • 3
    I'd make it `.bind('paste keyup blur', ...)` - I've used code similar to yours in the past but I find cross-browser support for the `paste` event is a bit sketchy and drag'n'drop doesn't trigger paste or keyup. Adding in `blur` catches everything that gets by the other events, even if a little late. – nnnnnn Aug 23 '11 at 04:36
  • It isn't working for me either. Specifically, I can paste long test into the textarea using the right-click context menu (Firefox 6). – Kobi Aug 23 '11 at 04:36
  • @Kobi So much for the `paste` event working then. Same happened for me. I'll make an edit. – alex Aug 23 '11 at 04:38
  • @mark - if it doesn't work at all (as compared to the special cases Kobi and I pointed out), please confirm where on your page you put the code - should be in the document ready function (or at least at the bottom after the textareas). – nnnnnn Aug 23 '11 at 04:42
  • @alex: I don't know why but it prints `function(i, val) { return val.substr(0, 5); }` in text area every time. – Harry Joy Aug 23 '11 at 04:52
  • @mark Are you using an old version of jQuery? I made an edit. – alex Aug 23 '11 at 05:09
  • `$(this).val((function(i, val) { return val.substr(0, 5); })());` – ant_Ti Aug 23 '11 at 06:37
  • @ant What is your comment about? – alex Aug 23 '11 at 06:41
  • @alex: I'm using Jquery 1.3. Is it good to use this version? Which version I should use? – Harry Joy Aug 23 '11 at 07:14
  • @mark I would always use the latest if I had the choice. The latest is `1.6.2`. – alex Aug 23 '11 at 07:23
  • @alex: which one should I download: `jQuery1.6.2.js` or `jQuery1.6.2-min.js` ? – Harry Joy Aug 23 '11 at 08:54
  • @mark Use the minified one in a production environment. Better still, use the one hosted on [Google's CDN](http://code.google.com/apis/libraries/devguide.html#jquery). – alex Aug 23 '11 at 09:23
  • @alex fix for executing function and not writing it to textarea – ant_Ti Aug 23 '11 at 11:01
0

Horrible and aggressive way

setInterval(function(){
    $('textarea').each(function(){
        if (this.value.length > 5){
            this.value = this.value.substr(0,5);
        }
    })
}, 1)

http://jsfiddle.net/YMsEF/

YOU
  • 120,166
  • 34
  • 186
  • 219
-1
var maxLettersCount = 3;

$('textarea').bind('keydown paste', function(event) {
    var textarea = $(event.target),
        text = textarea.val(),
        exceptionList = {
            8: true,
            37: true,
            38: true,
            39: true,
            40: true,
            46: true
        };

    if (event.type == 'keydown' && text.length >= maxLettersCount && !exceptionList[event.keyCode]) {
        return false;
    } else if (event.type == 'paste') {
        setTimeout(function() {
            textarea.val(textarea.val().substring(0, maxLettersCount));
        }, 1);
    }
})
ant_Ti
  • 2,385
  • 16
  • 14