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!
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!
Share Improve this question asked Nov 8, 2017 at 11:01 S.PearsonS.Pearson 1231 gold badge1 silver badge9 bronze badges 3 |5 Answers
Reset to default 10Try 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>
keyup
event, and within it, check the length of the input. If the condition matches, call the javascript code you want. – dlopez Commented Nov 8, 2017 at 11:04keyup
orkeydown
event and check if length is the same than your max, then display your message – Kaddath Commented Nov 8, 2017 at 11:04