javascript 在移动浏览器上强制执行 maxlength 属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17439487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 08:19:32  来源:igfitidea点击:

Enforcing the maxlength attribute on mobile browsers

javascriptjqueryhtmlinputmaxlength

提问by mdurchholz

I have an a text input with a maximum length:

我有一个最大长度的文本输入:

<input type="text" name="name" maxlength="50">

This has been working fine on all the desktop browsers I've tried, but the maximum length does not seem to be enforced on mobile browsers.

这在我尝试过的所有桌面浏览器上都运行良好,但似乎没有在移动浏览器上强制执行最大长度。

Is there any way to get mobile browsers to enforce maxlength? I am open to using JavaScript and/or jQuery in the solution.

有没有办法让移动浏览器强制执行maxlength?我愿意在解决方案中使用 JavaScript 和/或 jQuery。

采纳答案by jedmao

Try this one:

试试这个:

var $input = $('input')
$input.keyup(function(e) {
    var max = 5;
    if ($input.val().length > max) {
        $input.val($input.val().substr(0, max));
    }
});

jsFiddle here: http://jsfiddle.net/fttk2/1/

jsFiddle在这里:http: //jsfiddle.net/fttk2/1/

回答by littleboots

var max = 1

input.addEventListener('keyup', function (event) {
    event.target.value = event.target.value.substring(0, max)
})

回答by doublejosh

Universal jQuery way to enforce the stated maxlengthof a form field. (I needed it for sessionStorage, localStorage, and param overrides.) Code optimized for readability.

强制声明maxlength表单字段的通用 jQuery 方式。(我需要它用于 sessionStorage、localStorage 和 param 覆盖。)针对可读性进行了优化的代码。

$('input').on('change', function () {
  var max = $(this).attr('maxlength'),
      val = $(this).val(),
      trimmed;

  if (max && val) {
    trimmed = val.substr(0, max);
    $(this).val(trimmed);
  }
});

回答by COMPUTER KICK

I'd suggest something a bit more simple. The aboves didn't work for me unless there was a space added for the field to pick up on it... or if I hit submit right after, it still passed the information.

我会建议一些更简单的东西。以上对我不起作用,除非为该字段添加了一个空间以供选择……或者如果我在此之后立即点击提交,它仍然通过了信息。

if($(".input") > 20){$(".input") = input.slice(0,20)};

回答by scel.pi

var maxLength = 10;
var field = $('#myinput');
field.keydown( function(e)
{
    if ( $(this).val().length >= maxLength ) e.preventDefault();
});