How to prevent user to enter text in textarea after reaching max character limit

后端 未结 9 1472
盖世英雄少女心
盖世英雄少女心 2020-11-29 01:52

I want to prevent user to enter text in textarea once it reaches a max character limit. What was happening that when i reached to max limit then my text-area scroll-bar move

9条回答
  •  隐瞒了意图╮
    2020-11-29 02:32

    You could directly give maxlength to textarea to disable itself. But, you want to showing appropriate message then use keyup event for default behavior and textarea length for calculating charcter and display suitable message.

    HTML

    jQuery

    $(function(){
        var max = parseInt($("#tarea").attr("maxlength"));
      $("#count").text("Characters left: " + max);
        $("#tarea").keyup(function(e){
            $("#count").text("Characters left: " + (max - $(this).val().length));
        if($(this).val().length==max)
            $("#msg").text("Limit Reached....");
            else
            $("#msg").text("");
        });
    });
    

    Demo Fiddle

提交回复
热议问题