Skip to content

Instantly share code, notes, and snippets.

@pokk
Last active March 31, 2017 07:57
Show Gist options
  • Save pokk/d660dc645d42d1b114ae998e13c04188 to your computer and use it in GitHub Desktop.
Save pokk/d660dc645d42d1b114ae998e13c04188 to your computer and use it in GitHub Desktop.
Limit the number of lines in Textarea

Introduction

Limit the number of lines in Textarea.

Html

<textarea data-limit-rows="true" cols="60" rows="4"></textarea>

Javascript

$(document).ready(function ()
{
    $('textarea[data-limit-rows=true]').on('keypress', function (event)
    {
        var textarea = $(this);
        var numberOfLines = (textarea.val().match(/\n/g) || []).length + 1;
        var maxRows = parseInt(textarea.attr('rows'));
    
        if (event.which === 13 && numberOfLines === maxRows )
        {
            return false;
        }
    });
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment