use*_*377 13 javascript jquery
当用户在输入字段中输入时,是否有任何选项可以使用此代码而不显示字母或字符?这是我已经尝试过的代码,我想保留它,但是现在当我在输入中编写受限制的字符时,它会显示它们.我需要将输入留空
编辑:我不想更改代码,因为这在平板电脑上很有用(其他限制字符函数不会).唯一的问题是你按下受限制的字符会延迟
码:
function checkInput(ob){
var invalidChars = /[^0-9]/gi
if(invalidChars.test(ob.value)) {
ob.value = ob.value.replace(invalidChars,"");
}
};
Run Code Online (Sandbox Code Playgroud)
HTML:
<input class="input" maxlength="1" onChange="checkInput(this)" onKeyup="checkInput(this)" type="text" autocomplete="off"/>
Run Code Online (Sandbox Code Playgroud)
CJ *_*mki 14
你可以尝试这个,
$('.input').keyup(function () {
if (!this.value.match(/[0-9]/)) {
this.value = this.value.replace(/[^0-9]/g, '');
}
});
Run Code Online (Sandbox Code Playgroud)
更新 :
你可以尝试这个代码,
$(document).ready(function() {
$(".input").keydown(function (e) {
// Allow: backspace, delete, tab, escape and enter
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
// Allow: Ctrl+A
(e.keyCode == 65 && e.ctrlKey === true) ||
// Allow: home, end, left, right
(e.keyCode >= 35 && e.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
});
Run Code Online (Sandbox Code Playgroud)
更新为安卓:
<EditText
android:id="@+id/editText1"
android:inputType="number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_marginTop="58dp"
android:layout_toRightOf="@+id/textView1"
android:maxLength="1" >
</EditText>
Run Code Online (Sandbox Code Playgroud)
我认为它可以帮助你...使用android:inputType="number"你可以做到这一点.
FWD*_*ker 10
到目前为止给出的所有答案至少都存在以下可访问性问题之一:
value,从而重置插入符的位置。pattern属性,但是在提交表单之前不会提供反馈。在插入之前实际验证输入不是一个更好的主意吗?
该事件在输入值更改之前beforeinput触发。该事件有一个属性,描述用户想要添加到输入字段的内容。在事件处理程序中,您只需检查属性,如果包含不允许的字符,则停止事件链。datadata
我们最终得到以下非常简单、非常短的代码。
const input = document.getElementById("input");
const regex = new RegExp("^[0-9]*$");
input.addEventListener("beforeinput", (event) => {
if (event.data != null && !regex.test(event.data))
event.preventDefault();
});Run Code Online (Sandbox Code Playgroud)
<label for="input">Enter some digits:</label>
<input id="input" />Run Code Online (Sandbox Code Playgroud)
一些结束语:
title属性来显示解释预期格式的工具提示。按键和粘贴事件的组合可以解决问题:
var text = document.getElementById('text');
text.onkeypress = text.onpaste = checkInput;
function checkInput(e) {
var e = e || event;
var char = e.type == 'keypress'
? String.fromCharCode(e.keyCode || e.which)
: (e.clipboardData || window.clipboardData).getData('Text');
if (/[^\d]/gi.test(char)) {
return false;
}
}Run Code Online (Sandbox Code Playgroud)
<input class="input" maxlength="10" id="text" type="text" autocomplete="off" />Run Code Online (Sandbox Code Playgroud)
此代码可防止输入或粘贴除数字之外的任何内容.此外,不会显示闪烁和无效字符.
适用于IE7 +.
| 归档时间: |
|
| 查看次数: |
54806 次 |
| 最近记录: |