如何使用JavaScript检查数组值与用户输入的值?

时间:2017-02-22 14:48:02

标签: javascript html5 forms

初学者到JavaScript和HTML5(前一段时间学会了它,直到今天才使用它。)

所以,我花了一些时间在网上寻找答案,但找不到我想要的东西(也许我错过了什么)。我遇到的问题是我创建了一个表单,要求用户提供他们的姓名,ID和电子邮件(如果需要)。现在,在现实世界中,ID和名称将存储在数据库中,其中将针对数据库检查用户输入数据;但由于这是一个课堂作业,我们被要求创建一个由三名学生组成的数组,以便根据用户输入数据进行检查。

这是我的HTML5网站代码:

<!DOCTYPE html>
<html lang = "en">
<head>
<title>Student Transaction Form</title>
<meta charset="UTF-8"/>
<style>
p  {
    color: red;
    font-family: Times New Roman, serif;
    font-size: 160%;
 }
</style>
</head>
<body>
<div style="text-align:center;">
<FORM METHOD="POST" id="the-form" action="#" >
<TABLE BORDER="1" align = "center" >
<caption style="font-size:30px">Student Transaction Form</caption>
  <TR>
    <TD style="font-size:18px">Student Name:</TD>
    <TD>
      <INPUT TYPE="TEXT" required = "required" placeholder = "Input Name" NAME="name" SIZE="25">
    </TD>
	<TD style="font-size:18px"><p>Required</p></TD>
  </TR>
  <TR>
    <TD style="font-size:18px">Student Number:</TD>
    <TD><INPUT TYPE="TEXT" pattern=".{8,8}" required = "required" placeholder = "Input Number" NAME="number" SIZE="25"></TD>
	<TD style="font-size:18px"><p>Required</p></TD>
  </TR>
  <TR>
    <TD style="font-size:18px">Student Email:</TD>
    <TD><INPUT TYPE="email" NAME="email" SIZE="25" ></TD>
	<TD style="font-size:18px">
	    <script type="text/javascript">
        function ShowHideDiv(chkEmail) 
		{
            var dvEmail = document.getElementById("dvEmail");
            dvEmail.style.display = chkEmail.checked ? "block" : "none";
        }
	    </script>
	
<div id="dvEmail" style="display: none">
    <p>Required</p>
    </div>
    </TD>
  </TR>
  <TR>
  <TD></TD>
    <TD>
 <form id = "form1">
 <label for="chkEmail">
    <input type="checkbox" id="chkEmail" onclick="ShowHideDiv(this)" />
    Email me a transaction comfirmation
</label>
</form></TD>
  </TR>
</TABLE>
<P><INPUT TYPE="SUBMIT" VALUE="Submit" NAME="B1"></P>
</FORM>
</body>

目前的代码只是确保密码(ID)有效(有8个字符),如果勾选复选框,则需要发送电子邮件。

所以,我的问题是:如何创建一个学生姓名和ID相互连接的数组(意思是如果名称正确但ID是另一个人的话,那就是标记为不正确)以及如何使用用户输入数据运行检查?

例如,如果用户在ID框中输入Bill Smith作为名称和59683471,则在提交时会检查ID为59683471的Bill Smith是否存在;如果没有,则禁止提交。如果它们确实存在,那么一切都很好,并且可以提交表格。

谢谢。

编辑:

功能:

<script type ="text/javascript">
function checkall(Submit)
{
var name = document.getElementById("studentName").value;
var id = document.getElementById("studentNumber").value;
	var studentArray = 
	[
	{"Name": "Thomas Livshits", "Id": "33138463"},
	{"Name": "James Maro", "Id": "33138743"},
	{"Name": "Bill Smith", "Id": "33138356"},
	];
studentArray.forEach(function(student){
    if(id == student.Id && name == student.Name)
        console.log("Found a match for student: " + student.Name);
});
}
</script>

和提交部分:

<P><INPUT TYPE="SUBMIT" id = "Submit" VALUE="Submit" NAME="B1" onsubmit = "checkall(this); return false;"></P>

3 个答案:

答案 0 :(得分:1)

您可能希望创建一个嵌套数组,如下所示:

var userArray = [
    {name: "firstUser", ID: "firstID", email: "firstEmail"},
    {name: "secUser", ID: "secID", email: "secEmail"}, ...
]

然后准备一个循环:

var name = document.getElementById("NAME_DIV").value;
var id = document.getElementById("ID_DIV").value;
var email = document.getElementById("EMAIL_DIV").value;

for (i=0; i<userArray.length; i++) {
    var a = userArray[i].name;
    var b = userArray[i].ID;
    var c = userArray[i].email;

    if (a == name && b == id && c == email) {
         //do something
    };
};

希望这有帮助!在我的手机上键入它可能是一个小的语法错误,但逻辑应该得到你正在寻找的!

答案 1 :(得分:0)

我会在学生ID和名称id元素中添加input属性。然后使用document.getElementById(...).value获取每个元素的值。例如,您可以使用学生姓名:

<INPUT TYPE="TEXT" id = "studentName" ... NAME="name" SIZE="25">

然后通过document.getElementById("studentName").value获取值。接下来,您可以创建一个对象数组,该对象具有两个属性,其中一个属性用于Name,另一个用于Id

var studentArray = [
    {"Name": "StudentName1", "Id": "id_1"},
    {"Name": "StudentName2", "Id": "id_2"},
    ...
];

然后最后检查你可以循环遍历该数组并检查数组项的Name和Id属性是否与输入匹配。以下是一个简单的例子:

&#13;
&#13;
var inputStudentID = "id_2";
var inputStudentName = "StudentName2";

var studentArray = [
    {"Name": "StudentName1", "Id": "id_1"},
    {"Name": "StudentName2", "Id": "id_2"},
    {"Name": "StudentName3", "Id": "id_3"}
];

studentArray.forEach(function(student){
    if(inputStudentID == student.Id && inputStudentName == student.Name)
        console.log("Found a match for student: " + student.Name);
});
&#13;
&#13;
&#13;

答案 2 :(得分:0)

我认为最好的方法是将.js文件中的所有脚本和.css文件中的所有CSS放在一起,让HTML有一个干净的代码。请参阅下面的示例。另外,请在https://jsfiddle.net/uyg3xvgz/上找到要测试的代码。

HTML

<!DOCTYPE html>
 <html>
  <head>
   <meta charset="utf-8">
   <title>Student Transaction Form</title>
   <!-- CSS file include -->
   <link rel="stylesheet" href="css.css">
  </head>
  <body>
    <div class="container">
     <form id="contact" action="#" method="post">
      <h3>Student Transaction Form</h3>
      <h4>Please fill the form below.</h4>
      <fieldset>
        <input placeholder="Your name" type="text" tabindex="1" id="student_name" required autofocus>
      </fieldset>
      <fieldset>
        <input placeholder="Your ID" type="text" tabindex="2" id="student_id" required>
      </fieldset>
      <fieldset>
        <input placeholder="Your Email Address" type="email" tabindex="3" id="student_email">
      </fieldset>
      <fieldset>
        <button name="submit" type="submit" id="submit_form">Submit</button>
      </fieldset>
      <p class="copyright">Designed by <a href="https://colorlib.com" target="_blank" title="Colorlib">Colorlib</a></p>
    </form>
  </div>
  <!-- JavaScript file include -->
  <script type="text/javascript" src="js.js"></script>
 </body>
</html>

CSS

@import url(https://fonts.googleapis.com/css?family=Roboto:400,300,600,400italic);
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  -webkit-font-smoothing: antialiased;
  -moz-font-smoothing: antialiased;
  -o-font-smoothing: antialiased;
  font-smoothing: antialiased;
  text-rendering: optimizeLegibility;
}

body {
 font-family: "Roboto", Helvetica, Arial, sans-serif;
 font-weight: 100;
 font-size: 12px;
 line-height: 30px;
 color: #777;
 background: #4CAF50;
}

.container {
  max-width: 400px;
  width: 100%;
  margin: 0 auto;
  position: relative;
}

#contact input[type="text"],
#contact input[type="email"],
#contact input[type="tel"],
#contact input[type="url"],
#contact textarea,
#contact button[type="submit"] {
 font: 400 12px/16px "Roboto", Helvetica, Arial, sans-serif;
}

#contact {
 background: #F9F9F9;
 padding: 25px;
 margin: 150px 0;
 box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.2), 0 5px 5px 0 rgba(0, 0, 0, 0.24);
}

#contact h3 {
 display: block;
 font-size: 30px;
 font-weight: 300;
 margin-bottom: 10px;
}

#contact h4 {
 margin: 5px 0 15px;
 display: block;
 font-size: 13px;
 font-weight: 400;
}

fieldset {
 border: medium none !important;
 margin: 0 0 10px;
 min-width: 100%;
 padding: 0;
 width: 100%;
}

#contact input[type="text"],
#contact input[type="email"],
#contact input[type="tel"],
#contact input[type="url"],
#contact textarea {
 width: 100%;
 border: 1px solid #ccc;
 background: #FFF;
 margin: 0 0 5px;
 padding: 10px;
}

#contact input[type="text"]:hover,
#contact input[type="email"]:hover,
#contact input[type="tel"]:hover,
#contact input[type="url"]:hover,
#contact textarea:hover {
 -webkit-transition: border-color 0.3s ease-in-out;
 -moz-transition: border-color 0.3s ease-in-out;
 transition: border-color 0.3s ease-in-out;
 border: 1px solid #aaa;
}

#contact textarea {
 height: 100px;
 max-width: 100%;
 resize: none;
}

#contact button[type="submit"] {
 cursor: pointer;
 width: 100%;
 border: none;
 background: #4CAF50;
 color: #FFF;
 margin: 0 0 5px;
 padding: 10px;
 font-size: 15px;
}

#contact button[type="submit"]:hover {
 background: #43A047;
 -webkit-transition: background 0.3s ease-in-out;
 -moz-transition: background 0.3s ease-in-out;
 transition: background-color 0.3s ease-in-out;
}

#contact button[type="submit"]:active {
 box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.5);
}

.copyright {
 text-align: center;
} 

#contact input:focus,
#contact textarea:focus {
 outline: 0;
 border: 1px solid #aaa;
}

::-webkit-input-placeholder {
 color: #888;
}

:-moz-placeholder {
  color: #888;
}

::-moz-placeholder {
 color: #888;
}

:-ms-input-placeholder {
 color: #888;
}

JS

let validate_user = () => {
  //declare variables
  let ob = {},
   student_name = "",
   student_id = "",
   student_email = "";

  // initialize variables
  student_name = document.getElementById("student_name").value;
  student_id = document.getElementById("student_id").value;
  student_email = document.getElementById("student_email").value;

  //add object to simulate as a database
  ob['john'] = {name: "john", ID: "123", email: "john@john.com"};
  ob['michael'] = {name: "michael",ID: "456", email: "michael@michael.com"};
  ob['smith'] = {name: "smith",ID: "789", email: "smith@smith.com"};

  let finder = (ob, student_name, student_id) => {
   // declare variable
   let res = "";

   // search function | returns found object or 0
   let search = (ob, search_value) => {
     return (search_value in ob ? ob[search_value] : 0);
   }
   return search(ob, student_name).ID === student_id ? res = "Logged In" : res = "Oops, wrong user or ID";
 };

 //alert user
  alert(finder(ob, student_name, student_id));
}

//add event listener to submit button
document.getElementById("submit_form").addEventListener("click", validate_user);