Reputation: 7164
I have this code, it displays word count and applies an upper word limit. Can you tell me how I can change this code to apply lower limit? For example if user enters 299 words and hits enter, a pop up should appear and say, you didn't enter enough words. Thanks.
$("#TextArea").on('keyup', function () {
var words = this.value.match(/\S+/g).length;
if (words > 300) {
var trimmed = $(this).val().split(/\s+/, 300).join(" ");
$(this).val(trimmed + " ");
}
else {
$('#display_count2').text(words);
$('#word_left2').text(300 - words);
}
});
});
Upvotes: 0
Views: 45
Reputation: 5574
You need to add keydown event on that text area, and your event handler function should be something like this.
function onKeyDown(e){
if(e.keyCode == 13){ //for enterkey
var words = this.value.match(/\S+/g).length;
if(words >= 300){
//Your success code
}else{
alert("You didn't enter enough words");
}
}
}
Upvotes: 1
Reputation: 1148
You'll need to add a keypress event to have it work when enter is pressed. If you want it to work from anywhere in your form, you could add it on the document. That way it will be run no matter where enter is pressed.
$(document).keypress(function(e) {
if(e.which == 13) {
checkWordLimit();
}
});
You could then hook this up to a function that checks the word length
function checkWordLimit() {
var words = this.value.match(/\S+/g).length;
if (words < 300) {
alert("You need to enter at least 300 words!");
} else {
$('#display_count2').text(words);
$('#word_left2').text(300 - words);
}
}
If you want to keep the word count text updated, then just keep calling that function in the keyup event:
$("#TextArea").on('keyup', function () {
checkWordLimit();
});
To have it check before it submits the form (on a button click), then you can change the function to return true/false
based on the word count check, and then submit the form if it is successful. Note that this is for a regular button, not a submit button. If it's a submit button, then the submit
event in the form will need to be intercepted.
$("#SomeButton").on('click', function () {
if(checkWordLimit()) {
$("#SomeForm").submit();
}
});
Upvotes: 1