Skip to content Skip to sidebar Skip to footer

Validating User Input To Prevent Duplicate ID

I'm trying to create new 'student' objects each time a user inputs User ID, first name, last name, and clicks a button. I think I've made it to that point so far, but I'm trying to

Solution 1:

Here is a working snippet. Your ìds was always set to empty array because it was inside your function

  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");
      
    }


  }
<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>

Post a Comment for "Validating User Input To Prevent Duplicate ID"