0

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); } }); }); 

2 Answers 2

1

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(); } }); 
Sign up to request clarification or add additional context in comments.

2 Comments

What if user clicks enter button, instead of pressing enter. And I want to display word count real time, I mean it should increase when word count is increasing. Thanks.
If it's a submit button, then you could change the function to return true or false, and submit the form based on the return result. I'll update the question
1

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"); } } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.