Computer Magic Logo
Limit number of characters

Monday, June 12, 2017

Published by Aristotelis Pitaridis

A good practice when we have a limited number of characters for an input is to inform the visitor of the site about the number of characters left to type. The following example demonstrates how to restrict the user from typing more than 20 characters and inform him about the remaining number of characters left in order to reach the predefined characters limit.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <input type="text" id="username" />
    <div id="charsLeft">50 characters left</div>

    <script type="text/javascript" src="http://code.jquery.com/jquery-1.12.4.min.js"></script>
    <script type="text/javascript">    
        $(function () {
            var limit = 20;

            $("#username").keyup(function () {
                var len = $(this).val().length;
                if (len > limit) {
                    this.value = this.value.substring(0, limit);
                    len = limit;
                }

                $('#charsLeft').text(limit - len + " characters left");
            });
        });   
    </script>
</body>
</html>