If input maxlength is reached do something

S.Pearson picture S.Pearson · Nov 8, 2017 · Viewed 9.9k times · Source

I have a maxlength of 11 for an input field. I would like to perform a jQuery function when the maxlength has been met and the user keeps trying to type, so instead of it not doing anything, it'd show a message.

Please could you give me some pointers?

Thanks in advance!

Answer

Carsten Løvbo Andersen picture Carsten Løvbo Andersen · Nov 8, 2017

Try this: IT will alert a message when the user hits 11 characters.

$("input").on("keyup",function() {
  var maxLength = $(this).attr("maxlength");
  if(maxLength == $(this).val().length) {
    alert("You can't write more than " + maxLength +" chacters")
  }
})

Demo

$("input").on("keyup",function() {
  var maxLength = $(this).attr("maxlength");
  if(maxLength == $(this).val().length) {
    alert("You can't write more than " + maxLength +" chacters")
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input maxlength="11" />