限制 JQuery 中文本字段的字数
我正在修改一些 jquery 代码来限制文本字段的字数,但我不知道如何获取该值。代码如下:
<script>
var $limitWords = 20;
var $wordCount = $('#count').val();
$(document).ready(function(){
$("#edit-field-message-0-value").keyup(function() {
$('#count').html($('#edit-field-message-0-value').val().split(/\b[\s,\.-:;]*/).length);
if ($wordCount > $limitWords) {
$('#edit-field-message-0-value').addClass('error');
} else {
$('#edit-field-message-0-value').addClass('not-error');
}
});
});
</script>
具体来说,“$wordCount”应该等于什么才能返回当前值?
我认为这应该很容易,但我似乎无法弄清楚。
有什么想法吗?
谢谢,斯科特
I'm modding some jquery code to limit the word count of a textfield but I can't figure out how to get the value. Here's the code:
<script>
var $limitWords = 20;
var $wordCount = $('#count').val();
$(document).ready(function(){
$("#edit-field-message-0-value").keyup(function() {
$('#count').html($('#edit-field-message-0-value').val().split(/\b[\s,\.-:;]*/).length);
if ($wordCount > $limitWords) {
$('#edit-field-message-0-value').addClass('error');
} else {
$('#edit-field-message-0-value').addClass('not-error');
}
});
});
</script>
Specifically, what should "$wordCount" be equal to to return the current value?
I think it should be easy, but I can't seem to figure it out.
Any ideas?
Thanks, Scott
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我不太明白 $wordCount 变量。我相信您可能正在尝试执行以下操作:
我还假设您想存储当前计数:
I don't quite understand the $wordCount variable. I believe you may be trying to do the following:
I am also going to presume you wanted to store the current count:
这只是对上面的扩展,来自 Pritam 的很好的答案,我发现它的行为很奇怪并且改变了
var wordcount = $this.val().split(/\b[\s,.-:;]*/ ).length - 1;
至:
var wordcount = jQuery.trim($this.val()).split(/\b[\s,.-:;]*/).length;
这对奇怪的字数统计行为进行排序(如果您将值显示给用户以获取反馈)
This is just expanding on the above, great answer from Pritam, I found it behaved quite oddly and changed
var wordcount = $this.val().split(/\b[\s,.-:;]*/).length - 1;
To:
var wordcount = jQuery.trim($this.val()).split(/\b[\s,.-:;]*/).length;
This sorts the quirky wordcount behaviour (if you're displaying the value back to the user for feedback)
以下脚本不允许您输入超过
limitWord
的内容:The following script won't let you enter more than
limitWord
:如果我理解正确,您需要将代码放在输入/文本区域的事件处理程序中获取值,例如在按键事件的事件处理程序中。这样,您可以限制用户在输入/文本区域中输入文本时的字数。
If I've understood you correctly, you need to put the code to get the value inside an event handler for the input/textarea, for example in an event handler foe the keypress event. This way you can restrict the number of words whilst the user is entering text into the input/textarea.
由于我们不知道“#count”元素是什么,因此我从使用 html(...) 设置值的方法中获取了队列。所以,这应该有效:
Since we don't know what the "#count" element is, I took the queue from the method that sets the value using html(...). So, this should work: