问题
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
回答1:
I don't quite understand the $wordCount variable. I believe you may be trying to do the following:
$("#edit-field-message-0-value").keyup(function() {
var $this = $(this);
var wordcount = $this.val().split(/\b[\s,\.-:;]*/).length;
if (wordcount > $limitWords) {
$this.addClass('error');
} else {
$this.addClass('not-error');
}
});
I am also going to presume you wanted to store the current count:
$("#edit-field-message-0-value").keyup(function() {
var $this = $(this);
var wordcount = $this.val().split(/\b[\s,\.-:;]*/).length;
if (wordcount > $limitWords) {
$('#count').html($limitWords);
$this.addClass('error');
} else {
$('#count').html(wordcount);
$this.addClass('not-error');
}
});
回答2:
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)
回答3:
The following script won't let you enter more than limitWord
:
var limitWord = 20;
var maxchars = 0;
$("#edit-field-message-0-value").keyup(function() {
$this = $(this);
var wordcount = $this.val().split(/\b[\s,\.-:;]*/).length - 1;
if (wordcount < limitWord) {
chars = $this.val().length;
}
else{
var text = $(this).val();
var new_text = text.substr(0,chars);
$(this).val(new_text);
}
});
回答4:
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.
回答5:
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:
var $wordCount = $('#count').html();
来源:https://stackoverflow.com/questions/1579408/limit-word-count-of-a-textfield-in-jquery