简体   繁体   English

使用 Jquery 限制输入文本

[英]Limit input text using Jquery

I am using Tawk to chat in my website.我正在使用 Tawk 在我的网站上聊天。 I want to limit the number of text to 11 digits.我想将文本数量限制为 11 位数字。

<input type="text" id="prechat2Field" title="Phone" value="" class="textInput" maxlength="20" placeholder=" Phone">

I can't change their core files.我无法更改他们的核心文件。 Can it be done using Jquery?可以使用 Jquery 完成吗?

You can override property maxlength for that element:您可以覆盖该元素的属性maxlength

 $('#prechat2Field').prop('maxlength',11);
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <input type="text" id="prechat2Field" title="Phone" value="" class="textInput" maxlength="20" placeholder=" Phone">

You can set the maxlength attr like below via jQuery:您可以通过 jQuery 像下面这样设置maxlength属性:

 $(document).ready(function(){ $("#prechat2Field").attr('maxlength',"11"); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <input type="text" id="prechat2Field" title="Phone" value="" class="textInput" maxlength="20" placeholder=" Phone">

<input type="text" id="prechat2Field" title="Phone" value="" class="textInput" maxlength="20" placeholder=" Phone">

To do this by jQuery:要通过 jQuery 做到这一点:

function restrict_length(value, maxChar){
    $(value).attr('maxlength',maxChar);
}

Another way of doing it (without maxlength ):另一种方法(没有maxlength ):

 var input = document.getElementById('prechat2Field') input.onkeypress = function(ev) { if (input.value.length >= 11) { return false } }
 <input type="text" id="prechat2Field" value="" placeholder="Phone">

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM