简体   繁体   English

HTML输入框仅包含特定数字

[英]HTML Input Box with specific numbers only

I need an input text-box that can accept only string of 0's and 1's like 00101110101. 我需要一个输入文本框,只能接受0和1的字符串,如00101110101。

<input type="number"></input> restricts any letters to be entered, however, we can input 1,2,3,4 and so on. <input type="number"></input>限制<input type="number"></input>任何字母,但是,我们可以输入1,2,3,4等等。 I need to restrict input string to consist only 0's and 1's. 我需要将输入字符串限制为仅包含0和1。

Any way to do in HTML or with Javascript aid? 在HTML或Javascript援助中的任何方式?

You can use a regular expression ( /[^01]/g ) and replace to remove anything except 0 and 1 from the input's value. 您可以使用正则表达式( /[^01]/g )并replace以从输入的值中删除除01之外的任何内容。

 document.getElementById("inp").oninput = function() { var v = this.value; // get the value from the input v = v.replace(/[^01]/g, ''); // replace anything that isn't 0 or 1 by '' this.value = v; // set the value of the input to the new value } 
 <input id="inp"/> 

If you want the user to still edit things in the middle, then use this: 如果您希望用户仍在中间编辑内容,请使用以下命令:

 document.getElementById("inp").oninput = function() { var pos = this.selectionStart; // save the position of the caret var v = this.value; v = v.replace(/[^01]/g, ''); this.value = v; this.selectionStart = pos; // restore it this.selectionEnd = pos; // so no text will be selected } 
 <input id="inp"/> 

Note that I don't recommend using this last approach, as I'm not sure how many browsers handle selectionStart and selectionEnd . 请注意 ,我不建议使用最后一种方法,因为我不确定有多少浏览器处理selectionStartselectionEnd

This may help you. 这可能对你有所帮助。

<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 49'>

Hope it will help. 希望它会有所帮助。 Regards. 问候。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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