Enforcing the maxlength attribute on mobile browsers

大兔子大兔子 提交于 2019-11-30 17:58:30

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/

var max = 1

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

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

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

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

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)};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!