If input maxlength is reached do something

Viewed 14834

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!

5 Answers

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

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

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.

$(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>

If you add the $(document) it will find all the inputs with maxlength attribute, even if you have created them after loading the page.

$(document).on("input keypress", "input[maxlength]", function (e) {
    var $input = $(e.currentTarget);
    if ($input.val().length >= $input.attr("maxlength")) {
        alert("Max length reached")
    }
});
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<input>

Related