密码框 - 使用javascript从输入字段获取值

时间:2015-05-27 10:39:07

标签: javascript css regex input get

有人知道如何制作像this图片这样的密码框吗?

此密码框将是网站/手机的第一页。用户必须插入4个数字(1 - 2 - 3 - 4)。如果他们不输入1 -2 - 3 - 4作为他们的密码,他们将会收到一个消息框,上面写着"密码错误"。如果输入正确,则会将其发送到下一页。 感谢帮助!

3 个答案:

答案 0 :(得分:0)

根据您的评论,在提供的图片中,您似乎想要为用户提供4个框,然后在其中,他们将输入他们的密码。

在这种情况下,我认为你根本不需要正则表达式。你需要做什么,在我看来,如下:

  1. 创建4个密码字段文本框。
  2. 在检查密码的部分,只需检查第一个框中是否存储了值1,第二个框中有2个,第三个框中有3个,第四个框中有4个。
  3. 由于您正在寻找特定的整个字符串值,而不是模式,因此不需要正则表达式。

答案 1 :(得分:0)

这是一个工作样本

var password = [1,2,3,4];

var pwdInputs = $("#pwdContainer input");
var inputs = pwdInputs.toArray();

pwdInputs.keyup(function(){
  if (this.value.length == this.maxLength) {
    if(inputs.indexOf(this) == inputs.length-1){
      testPassword();
    } else {
      $(this).next('input').focus();
    }
  }
});

function testPassword(){
  var valid = true;
  
  for(var i=0; i<inputs.length; i++){
    if(password[i] != inputs[i].value){
      valid = false;
      break;
    }
  }
  
  if(valid){
    console.log("Correct Password!");
    window.location.href = 'http://www.google.com';
  }else{
    console.log("Wrong Password!");
  }
}
div.box-big {
  background-color: grey;
  margin: auto;
  display:inline-block;
  padding: 10px;
  padding-top: 20px;
}

input.box-text {
  width: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="pwdContainer" class="box-big" >
  <input type="text" maxlength="1" class="box-text" >
  <input type="text" maxlength="1" class="box-text">
  <input type="text" maxlength="1" class="box-text">
  <input type="text" maxlength="1" class="box-text">
</div>

答案 2 :(得分:0)

您可能需要regular expression(正则表达式),可用于验证您的输入。

正则表达式字符串看起来像这样:\d{4}[0-9]{4},它基本上是严格匹配所有数字('\ d&#39;或0-9中的数字),所以只有四位数字才有效

&#13;
&#13;
<input type="password" pattern="[0-9]{4}" id="passcode" required onkeyup="checkIfValid()">
<p id="isValid"></p>
&#13;
&#13;
&#13;