Skip to content

Instantly share code, notes, and snippets.

@stranger26
Created October 14, 2016 17:33
Show Gist options
  • Save stranger26/05298db8ee0a8a4c0dd1a7a0c5e8716c to your computer and use it in GitHub Desktop.
Save stranger26/05298db8ee0a8a4c0dd1a7a0c5e8716c to your computer and use it in GitHub Desktop.
Text Area Max Length by Word Count implemented with Javascript
// TO DO
// Removes the last space input by user
// Ensure code runs after form is loaded
window.onload = function() {
// Main function
function maxLength(el, max) {
el.onkeyup = function() {
var charLength = el.value.length;
var wordLength = el.value.split(" ").length;
if (wordLength == max) {
el.setAttribute("maxlength", charLength+1);
} else if (wordLength > max) {
el.value.split(" ").slice(0, max).join(" ");
}
}
}
// Function call for element by data- attribute without value
maxLength(document.querySelector("[data-attribute]"), 10);
// Function call for element by data- attribute with value
maxLength(document.querySelector("[data-attribute='value']"), 10);
// Function call for element by class
maxLength(document.getElementByClassName("class"), 10);
// Function call for element by id
maxLength(document.getElementById("id"), 10);
// Function call for element by element tag
maxLength(document.getElementByTagName("tag"), 10);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment