首页 > 解决方案 > 如何在输入中只写一个符号?

问题描述

我想将输入字段限制为一个字母(使用 JS),在一个字母之后我想得到一个错误。怎么做?

标签: javascript

解决方案


你会想要这样的东西

香草JS

<input onkeydown="checkLen(this)" type="text" maxlength="1" />

function checkLen(e) {
  if (el.value.length > 1) {
    alert("ERROR");
  }
}

jQuery

$('#input').keydown( function(e){
    if ($(this).val().length > 1) { 
        alert('ERROR');
    }
});

推荐阅读