Skip to content

Instantly share code, notes, and snippets.

@EarthlingDavey
Last active December 18, 2019 10:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EarthlingDavey/d2d6151fa49cd7ad608c767511ce18c2 to your computer and use it in GitHub Desktop.
Save EarthlingDavey/d2d6151fa49cd7ad608c767511ce18c2 to your computer and use it in GitHub Desktop.
Word limit for ACF text input field
// This is a function to limit word count on ACF fields
// Add cu-helper__max-words-3 to the field class for a limit of 3 words
var maxWordHelperClass = 'cu-helper__max-words-';
$('#editor').on('keydown', '.acf-field[class*="' + maxWordHelperClass + '"] input', function (e) {
var maxWords = 0;
var $input = $(this);
if ($input.attr('data-max-words')) {
var maxWords = $input.attr('data-max-words');
} else {
var $field = $input.closest('.acf-field')
var classList = $field.attr('class').split(/\s+/);
$.each(classList, function (index, item) {
if (item.indexOf(maxWordHelperClass) >= 0) {
console.log(item);
var parts = item.split("-");
var maxWords = parts.pop();
$input.attr('data-max-words', maxWords);
}
});
}
// Split the text in the input and get the current number of words
var words = $input.val().split(/\s+/).length
// If the word count is > than the max amount and a space is pressed
// Don't allow for the space to be inserted
if (!$input.attr('data-announce')) {
// If the first two tests fail allow the key to be inserted
// Otherwise we prevent the default from happening
words >= maxWords && e.keyCode == 32 && e.preventDefault()
} else {
words >= maxWords && e.keyCode == 32 && (e.preventDefault() || alert('Word Limit Reached'))
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment