Reputation: 1894
I have one textarea
in which I want to allow only 30 words and remove remaining extra words:
$("#short_desc").keydown(function(e){
var d = $(this).val().split(/\b[\s,\.-:;]*/).length;
if(d > 30){
alert("Only 30 words allowed");
e.preventDefault();
// here i want to add logic how to remove words.
return false;
}
});
I have tried with character count but can't short out this logic. Can some one provide some hint?
I have one logic that count spaces and then count character count till 30 spaces and get sub string before that character count.
Upvotes: 2
Views: 580
Reputation: 7862
Instead remove the words; you could assign the 30 first words to the textarea
value.
The next code works well. The split()
delimiters are not deleted. I used capturing parentheses
: any captured text is included in the resulting string array.
NOTE:
You must use double the amount you want to limit. You should use 60.
I created a "constant"
MAX_WORDS_ALLOW
for make the things simplest.
var MAX_WORDS_ALLOW = 30;
// Change, keup and paste event.
$("#short_desc").on("change keyup paste", function(e){
var d = $(this).val().split(/\b[\s,\.-:;]*/).length;
if(d > MAX_WORDS_ALLOW ){
alert("Only "+MAX_WORDS_ALLOW +" words allowed: "+d);
e.preventDefault();
// Get the 30 first words
var thirty_Words = $(this).val().split(/(\b[\s,\.-:;]*)/, MAX_WORDS_ALLOW * 2).join("");
// Here I assign the 30 first words to textarea.
$(this).val(thirty_Words);
return false;
}
$("#numberWords").html(d);
});
// Initial text, for the JSFiddle example
$("#short_desc").val("Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus").change();
You can see this in action here: http://jsfiddle.net/xfhoc1gq/2/
Upvotes: 3