Skip to content

Instantly share code, notes, and snippets.

@rafiahmedd
Created September 10, 2021 10:19
Show Gist options
  • Save rafiahmedd/cc8b60256b8906bc128eadc185203375 to your computer and use it in GitHub Desktop.
Save rafiahmedd/cc8b60256b8906bc128eadc185203375 to your computer and use it in GitHub Desktop.
Text Counter with word limit
let max = $('.max').val();
$('.text').keydown(count);
function count(event) {
let len = $('.text').val().split(/[\s]+/);
if (len.length > max) {
if ( event.keyCode == 46 || event.keyCode == 8 ) {// Allow backspace and delete buttons
} else if (event.keyCode < 48 || event.keyCode > 57 ) {//all other buttons
event.preventDefault();
}
}
let wordsLeft = (max) - len.length;
$('.counter').val(wordsLeft);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment