嗨有没有办法限制textarea中具有与 maxlength 相同功能的单词使用jquery或coffeescript以及使用keyup函数,因为我需要显示一个准确的计数器。我一直在寻找,但无法找到办法。我试过这个,但它是在按键上,它允许用户粘贴超过250个单词。
$(document).on "keypress", '#company_desc', (e) ->
s = $("#company_desc").val()
s = s.replace(/(^\s*)|(\s*$)/g, "")
s = s.replace(/[ ]{2,}/g, " ")
s = s.replace(/\n /, "\n")
count = s.split(" ").length
$(".counter").html(250 - count + " words remaining")
if count == 250
key = (if e.charCode then e.charCode else (if e.keyCode then e.keyCode else 0))
switch key
when e.ctrlKey && key == keys[CTRL_A] then return true
when e.ctrlKey && key == keys[CTRL_C] then return true
when e.ctrlKey && key == keys[CTRL_X] then return true
when e.ctrlKey && key == keys[CTRL_Z] then return true
else return key == 46 || key == 8
答案 0 :(得分:0)
var maxWords = 150;
jQuery('textarea').keypress(function() {
var $this, wordcount;
$this = $(this);
wordcount = $this.val().split(/\b[\s,\.-:;]*/).length;
if (wordcount > maxWords) {
jQuery(".word_count span").text("" + maxWords);
alert("You've reached the maximum allowed words.");
return false;
} else {
return jQuery(".word_count span").text(wordcount);
}
});
fiddler:http://jsfiddle.net/qPvch/164/
答案 1 :(得分:0)
所以我想出了这个。
var maxWords = 250;
jQuery('textarea').keyup(function() {
var a, wordcount;
a = $(this).val();
a = a.replace(/(^\s*)|(\s*$)/g, "");
a = a.replace(/[ ]{2,}/g, " ");
a = a.replace(/\n /, "\n");
wordcount = a.split(" ").length;
if (wordcount == maxWords) {
$(this).val(a.substr(0, a.length));
}
if (wordcount > maxWords) {
$(this).val(a.substr(0, a.length - 1));
}
return jQuery(".word_count span").text(maxWords - wordcount + " words remaining");
});
$('textarea').bind("paste",function(e) {
e.preventDefault();
});
我使用.substr(0, a.length -1)
来切断单词并强制用户保留在maxWords中,我也禁用了textarea中的粘贴(这也禁用了右键单击粘贴)但我不认为这是最好的方法,如果用户仍然可以使用粘贴并在粘贴后自动剪切多余的单词,或者当用户已经达到maxlength
这样的最大单词时禁用它,则会更好。有什么建议?
这是我的小提琴 - JSFiddle
答案 2 :(得分:0)
你的textarea添加attr“maxlength”
试试这个。
$("your textarea id and class").attr("maxlength", 250);