将文本框上的用户输入限制为特定的字母

时间:2018-08-17 10:49:57

标签: javascript css html5

我有两个要限制用户的文本框,因此他只能在该文本框中使用 Y N 。我该如何实现

.yes_or_no{
  font-size:xx-large;
  font-weight:900;
  color:#000;
}
<input id="t1" class="yes_or_no" type="text" class="typing1"  name="txt1"   oninput="this.value = this.value.toUpperCase(),  this.value.replace(/[^0-9]/, '')"  maxlength="1" />
<input id="t2"class="yes_or_no" type="text" class="typing2"  name="txt2"   oninput="this.value = this.value.toUpperCase(),  this.value.replace(/[^0-9]/, '')"  maxlength="1" />

2 个答案:

答案 0 :(得分:4)

您快到了!除了将非数字字符替换为空白之外,您还可以将非YN之外的任何内容替换为空白。

请参阅以下演示:

<input type="text" class="typing1" name="txt1" id="t1" oninput="this.value = this.value.toUpperCase().replace(/[^YN]/, '')" maxlength="1" />
<input type="text" class="typing2" name="txt2" id="t2" oninput="this.value = this.value.toUpperCase().replace(/[^YN]/, '')" maxlength="1" />

答案 1 :(得分:1)

您必须定义一个仅接受Y或N的模式。-documentation

看看这就是您要寻找的东西。

不输入Y或N不会提交表单。

<form action="/action_page.php">
  Question?: <input type="text" name="question" pattern="^(?:Y\b|N\b)" maxlength="1" title="Introduce Y or N">
  <input type="submit">
</form>

相关问题