一旦达到给定数量的单词或字符(不包括空格),我正试图限制表单字段中文本框的长度。
我遇到的问题是,一旦达到上限,我就不知道如何限制子字符串最大长度变量。
我使用Callable.js (https://sacha.me/Countable/docs/)作为计数器脚本。
var wordL = 3;
var charL = 18;
var boxid = 'descr';
var area = document.getElementById(boxid);
function fixlength(boxid,wordlimit,charlimit,wordcount,charcount,allcount) {
if (charcount > charlimit || wordcount > wordlimit) {
/******************************
* The following line contains the problematic dynamic variable
*******************************/
area.value = area.value.substring(0, all);
}
}
function callback (counter) {
console.log(counter);
document.getElementById("wordsleft").innerHTML = wordL - counter.words;
document.getElementById("charsleft").innerHTML = charL - counter.characters;
fixlength(boxid,wordL,charL,counter.words,counter.characters,counter.all);
}
Countable.live(area, callback);<script src="https://raw.githubusercontent.com/RadLikeWhoa/Countable/master/Countable.js"></script>
<!DOCTYPE HTML>
<html>
<head>
<title>Test</title>
</head>
<body>
Words:<span id="wordsleft"></span> Chars:<span id="charsleft"></span>
<form>
<textarea id="descr" name"descr"></textarea>
</form>
</body>
</html>
发布于 2016-03-08 19:11:54
我怀疑一旦达到限制,您将需要阻止该文本区域接受用户输入。如果我是对的,您应该将一个onKeyPress事件侦听器附加到文本区域,一旦超过了这个限制,就应该使用return false。返回false意味着停止文本区域接受新字符。
发布于 2016-03-08 19:20:27
我已经测试了一个解决方案,它适用于您正在尝试的内容。
示例-使用jQuery
$("#id-here").keyup(function(){//下一行从字符串中删除空格
var characters = $("#id-here").val().replace(/\s/g,''); //设置最大长度
var max_length = 50;// if语句检查用户输入是否等于最大长度,如果是,textarea将获得只读属性属性,该属性将禁止用户输入更多文本
if(characters.length == max_length){
$("#id-here").attr("readonly","readonly");
}
});https://stackoverflow.com/questions/35875432
复制相似问题