Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If input maxlength is reached do something

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!

like image 892
S.Pearson Avatar asked Nov 08 '17 11:11

S.Pearson


People also ask

What is the maxLength attribute of a text field?

The maxLength attribute specifies the maximum number of characters allowed in a text field. Tip: To set or return the width of a text field, in number of characters, use the size property.

What does the maxLength property do?

The maxLength property sets or returns the value of the maxlength attribute of a text field. The maxLength attribute specifies the maximum number of characters allowed in a text field. Tip: To set or return the width of a text field, in number of characters, use the size property.

What is the maximum number of characters allowed in the input?

number. The maximum number of characters allowed in the <input> element. Default value is 524288. ❮ HTML <input> tag. #N#.

How to limit the max length of a textbox text?

It is very common to implement maxlength check in the client side(browser). For example, limit the address textbox within 50 characters or limit the content textarea within 1000 characters.


1 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" />
like image 172
Carsten Løvbo Andersen Avatar answered Oct 04 '22 23:10

Carsten Løvbo Andersen