Re: Adding character counter to a form field
This is one I did not that long ago, you just call it and pass it the schema name of the field, it will also check if someone is pasting too much text in (if there's browser support) - no warranty is provided.
function addCharacterCounter(fieldName){
//debugger;
let maxLength = $("#"+fieldName).attr("maxlength");
let formattedMaxLength = Number(maxLength).toLocaleString("en-US");
let currentLength = $("#"+fieldName).val().length.toLocaleString("en-US");
$( "<p style='float: right;'><span id='"+fieldName+"CharCounter'>"+currentLength+"</span><span>/"+formattedMaxLength+"</span></p>" ).insertAfter($("#"+fieldName))
// update counter on key event
$( "#"+fieldName ).on( "keyup", function(event) {
let fieldId = event.currentTarget.id;
let newLength = $("#"+fieldId).val().length.toLocaleString("en-US") ;
$("#"+fieldId+"CharCounter").text(newLength);
});
// put message on screen if attempt to paste too much text
// also takes into account pasting to replace selected text
const target = document.getElementById(fieldName);
target.addEventListener("paste", (e) => {
try{
let paste = (e.clipboardData || window.clipboardData).getData("text");
let clipLength = paste.length;
let existingLength = $("#"+e.currentTarget.id).val().length;
let maxLength = Number($("#"+e.currentTarget.id).attr("maxlength"));
// if there is text that is currently selected that will be replaced
// get the length of the selection
let selectedTextLength = window.getSelection().toString().length;
if((clipLength+existingLength-selectedTextLength) > maxLength ){
alert("Unable to paste content - content will exceed the maximum length for the field");
return false;
}
}
catch(err){
//do nothing
}
return true
});
}