Created
October 14, 2016 17:33
-
-
Save stranger26/05298db8ee0a8a4c0dd1a7a0c5e8716c to your computer and use it in GitHub Desktop.
Text Area Max Length by Word Count implemented with Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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