If input maxlength is reached do something

12,944

Solution 1

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" />

Solution 2

try this code

$(document).ready(function() {
  $("#text").keypress(function(e) {
    var length = this.value.length;
    if (length >= 11) {
      e.preventDefault();
      alert("not allow more than 11 character");
    }
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text">

Solution 3

You are looking for something like:

$("input").keypress(function(e){
    if(e.target.value.length==11){
        alert("maxlength reached");
    }
});

Obviously change to use the correct selector and alert/modal popup.

Solution 4

$(document).ready(function(){
$("input").keyup(function(){
var a = $(this).val().length;
if(a >= 11){
$(this).attr('maxlength','11')
alert("not allowed")
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input>
Share:
12,944

Related videos on Youtube

S.Pearson
Author by

S.Pearson

Updated on August 29, 2022

Comments

  • S.Pearson
    S.Pearson over 1 year

    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!

  • Marcono1234
    Marcono1234 over 4 years
    This also triggers for keys which do not write characters, e.g. entering 11 characters and then moving the cursor using the arrow keys triggers the alert. Or when trying to copy the input using Ctrl + C.
  • mickmackusa
    mickmackusa over 3 years
    This answer is missing its educational explanation.
  • mickmackusa
    mickmackusa over 3 years
    This answer is missing its educational explanation.
  • mickmackusa
    mickmackusa over 3 years
    This answer is missing its educational explanation.