Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't write if string is longer than a number

The user, if length's string is over 12 characters, can't write.This is my script ("mat" is the text field).

window.onload = function() {
  document.getElementById("mat").onchange = function() {
    if ((document.getElementById("mat").value.length) > 12) {
      document.getElementById("mat").value = document.getElementById("mat").value.substring(0, 12);
    }
  }
}

This code works properly, but the characters over 12 characters are deleted only if the text field it is no longer selected. How can I do?

like image 261
SlaaSh Avatar asked Dec 24 '22 08:12

SlaaSh


1 Answers

Why not use the maxLength property?

<input type="text" maxLength="12">

As of HTML 5, the textarea object also supports it:

<textarea maxLength="12"></textarea>
like image 179
Nick stands with Ukraine Avatar answered Dec 25 '22 22:12

Nick stands with Ukraine