As the discussion to this topic was already old/closed but it might be useful to one or the other. We had the problem that we wanted to limit the number of characters in a text field of the moodle database activity. Using Moodle 3.5.1 we found this solustion:
1. Javascript Template:
function init(){
var v = document.getElementById("xyz");
var cells = v.getElementsByTagName("label");
var status="";
for (var i = 0; i < cells.length; i++) {
status = cells[i].getAttribute("for");
}
var x = document.getElementsByName(status);
x[0].onblur = function() {myFunction(this)};
}
function myFunction(input) {
var wert = input.value.length;
while (wert > 24){
input.value=prompt("do not use more then 25 characters please");
if (input.value != null) { return input.value;}
}
}
window.onload = init;
2. add template
include id="xyz" i.e. in a tag
<table><tr ><td id="xyz">fieldname</td>
Javascript is now able to look up the unique field-id (via laber/for) and so it can use onblur() - input.value is checked when you leave the field and you will see the message ("do not use more then 25 characters please") in a prompt.
Tribute to Kathrin Schwarz!