验证用户输入以防止重复ID

时间:2016-10-06 13:23:40

标签: javascript

我正在尝试创建新的"学生"每次用户输入用户ID,名字,姓氏和单击按钮时的对象。 我想我到目前为止已经达到了这一点,但我试图确保无法添加多个具有相同ID的学生。我认为使用两个不同的变量循环可能是隔离潜在重复项的最佳方法,但是我唯一一次看到我的警报消息时实际上没有任何重复项。有人能用这个推动我朝着正确的方向前进吗?

继承我的代码:

<form>
ID Number:<br>
<input type="text" id="idNumber">
<br>
First name:<br>
<input type="text" name="firstName" id="fName">
<br>
Last name:<br>
<input type="text" name="lastName" id="lName">
</form>
<br>
<button type ="submit" onclick="myFunction(list)">Submit</button>
<div id = "container">
<ul id="list"></ul>
</div>

<script>
function myFunction(list){

    var ids =[];
    var student = new Object();
    student.idNo = document.getElementById("idNumber").value;

    student.firstName = document.getElementById("fName").value;
    student.lastName = document.getElementById("lName").value;

    for(var i = 0; i < 10; i++){
        for(var j = 1; j < 10 ; i++){
        ids.push(student.idNo);
        if(ids[i] == ids[j]){
        alert("Id already exists");
        }
        }
    }

    var text = " "+student.idNo+" "+student.firstName+" "+student.lastName;

    var li = document.createElement("li");
    li.addEventListener("mouseover", mouseOver, false);
    //li.addEventListener("click", mouseClick, false);
    var node = document.createTextNode(text);
    li.appendChild(node);
    document.getElementById("list").appendChild(li);
}


</script>

1 个答案:

答案 0 :(得分:2)

这是一个工作片段。您的ìds始终设置为空数组,因为它位于您的函数内

&#13;
&#13;
  var ids = [];

  function myFunction(list) {
    var student = new Object();
    student.idNo = document.getElementById("idNumber").value;
    student.firstName = document.getElementById("fName").value;
    student.lastName = document.getElementById("lName").value;

    if (ids.indexOf(student.idNo) == -1) {
      
      ids.push(student.idNo);
      var text = " " + student.idNo + " " + student.firstName + " " + student.lastName;
      var li = document.createElement("li");
      var node = document.createTextNode(text);
      li.appendChild(node);
      document.getElementById("list").appendChild(li);
      
    } else {
      
      alert("Duplicated ID");
      
    }


  }
&#13;
<form>
  ID Number:
  <br>
  <input type="text" id="idNumber">
  <br>First name:
  <br>
  <input type="text" name="firstName" id="fName">
  <br>Last name:
  <br>
  <input type="text" name="lastName" id="lName">
</form>
<br>
<button type="submit" onclick="myFunction(list)">Submit</button>
<div id="container">
  <ul id="list"></ul>
</div>
&#13;
&#13;
&#13;