/**
* Set the maximum characters allowed in a text element.
*/
function setMaxCharacters(id, size_limit) {
var input_value = document.getElementById(id).value;
if (input_value.length >= size_limit) {
document.getElementById(id).value = input_value.substring(0, (size_limit - 1));
}
}
// add the event listener and call the function - see https://www.w3schools.com/jsref/dom_obj_event.asp for events
document.getElementById("element-id").addEventListener('keydown', function() {
// call function on keydown.
setMaxCharacters("element-id", 4);
}, false);