jQuery Implementation Limits the Input Length of Text Boxes

  • 2021-07-10 18:33:52
  • OfStack

jQuery restricts text box input, including paste.


// Limit the input length of a text box 
$(function () {
 $(document).on("keypress", ".txt-valid-len", function (e) {
 if (e.keyCode == 8) {
 return true;
 }
 else {
 var len = $(this).data("maxlength") || 0;
 if (len > 0) {
 return (this.value.length <= len);
 }
 }
 return true;
 });
 // Paste 
 $(document).on("paste", ".txt-valid-len", function () {
 var len = $(this).data("maxlength") || 0;
 if (len > 0) {
 return ((this.value.length + event.clipboardData.getData('Text').length) <= len);
 }
 return true;
 });
 $(document).on("keyup input", ".txt-valid-len", function (e) {
 var keyCode = e.keyCode || e.which || e.charCode;
 if (keyCode == 46 || keyCode == 8) {
 }
 else {
 var len = $(this).data("maxlength") || 0;
 if (len > 0) {
 if (this.value.length > len) {
  this.value = com.cutStr(this.value, len, "");
 }
 }
 }
 });
});

Related articles: