简体   繁体   中英

Disable keyboard input excluding backspace

Using the javascript i am trying to disable users input after rich 80 charecters and if they press "Backspace" and remove some charecters then they can enter text again until rich again to 80. I have written code bellow but dont know why its not working. Any idea?

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script src="http://code.jquery.com/jquery-1.11.1.js" type="text/javascript"></script>
</head>
<body>


<input type="text" class="form-control" id="editText" aria-describedby="basic-addon2" value="Something">
<span class="input-group-addon" id="basic-addon2">/80</span>

    <script type='text/javascript'>

        $('#editText').keyup(updateCount);
        $('#editText').keydown(updateCount);

            function updateCount() {
            var limitText = "/80";
            var lengthNumber = $(this).val().length;
            if (lengthNumber>80) {
              $("#editText").keydown(false);
            }else{
              $("#editText").keydown(true);
            }
            $('#basic-addon2').text(lengthNumber+limitText);
        }

    </script>

</body>
</html>
<input type="text" name="usrname" maxlength="80"> 

您可以使用maxlength标签。

You can directly use input property maxlength="80":

<input maxlength="80">

https://jsfiddle.net/ramseyfeng/wph565xu/

If you cant use maxlength property, and you MUST use javascript / JQuery, you could use bellow code

var limitText = 10;
$('#editText').keydown(function(e){
    if ($(this).val().length > limitText)
    {
        if (e.keyCode != 8)
        {
          e.preventDefault();
          return false;
        }
    }
});

Demo : https://jsfiddle.net/5dctLbxq/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM