[英]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. 我正在使用JavaScript尝试在丰富了80个字符之后禁用用户输入,如果他们按“退格”键并删除了一些字符,那么他们可以再次输入文本,直到再次丰富到80个字符。我已经写了下面的代码,但是不知道为什么它不起作用。 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": 您可以直接使用输入属性maxlength =“ 80”:
<input maxlength="80">
https://jsfiddle.net/ramseyfeng/wph565xu/ https://jsfiddle.net/ramseyfeng/wph565xu/
If you cant use maxlength
property, and you MUST use javascript / JQuery, you could use bellow code 如果您不能使用
maxlength
属性,并且必须使用javascript / JQuery,则可以使用以下代码
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/ 演示: https : //jsfiddle.net/5dctLbxq/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.