简体   繁体   中英

Enforcing the maxlength attribute on mobile browsers

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.

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)
})

此问题是因为您的键盘上启用了预测文本,请将其禁用并重试

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)};

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);
  }
});

This problem is because predictive text is enabled on your mobile keyboard so disable predictive text.

<input autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" type="text" name="name" maxlength="50">
var maxLength = 10;
var field = $('#myinput');
field.keydown( function(e)
{
    if ( $(this).val().length >= maxLength ) e.preventDefault();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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