2017-02-22 71 views
0

初學者到JavaScript和HTML5(前一段時間學過,直到今天才使用它)。如何使用JavaScript檢查數組值與用戶輸入的值?

所以,我花了一些時間在網上尋找答案,但找不到我在找什麼(也許我失去了一些東西)。我遇到的問題是,如果需要,我創建了一個表單,要求用戶提供姓名,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> 
 
\t <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> 
 
\t <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> 
 
\t <TD style="font-size:18px"> 
 
\t  <script type="text/javascript"> 
 
     function ShowHideDiv(chkEmail) 
 
\t \t { 
 
      var dvEmail = document.getElementById("dvEmail"); 
 
      dvEmail.style.display = chkEmail.checked ? "block" : "none"; 
 
     } 
 
\t  </script> 
 
\t 
 
<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框中輸入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; 
 
\t var studentArray = 
 
\t [ 
 
\t {"Name": "Thomas Livshits", "Id": "33138463"}, 
 
\t {"Name": "James Maro", "Id": "33138743"}, 
 
\t {"Name": "Bill Smith", "Id": "33138356"}, 
 
\t ]; 
 
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>

回答

0

我認爲最好的方法是將所有腳本放在.js文件和所有的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: "[email protected]"}; 
    ob['michael'] = {name: "michael",ID: "456", email: "[email protected]"}; 
    ob['smith'] = {name: "smith",ID: "789", email: "[email protected]"}; 

    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); 
+0

謝謝,幫助我很多。 – Thomas

0

你可以做一個簡單的多維數組這樣的...

var myUsers = [ 
    ['Bill Smith', '59683461'], 
    ['Jane Doe', '23423526'] 
]; 

然後你查找用戶在陣列中,找到自己在未來的索引ID。順便說一下,在數組中查找值有多種方法。

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屬性是否與輸入匹配。下面是一個簡單的例子:

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

+0

會是相同方式實現電子郵件(在我的代碼被執行),在那裏你創建一個功能當提交按鈕被按下時,它會遍歷並檢查。一個像這樣的函數:'function checkall(Submit)'在哪裏調用提交ID提交還是不行?對不起,如果它應該是明顯的,只是沒有看到它。 – Thomas

+0

@Thomas是的,你可以使用'onsubmit'來做同樣的事情,然後在事件處理程序中用'e.preventDefault()'或'return false'來停止提交。 –

+0

有點困惑,對不起。那麼,它會是'onsubmit =「checkall(this)」'。然後''return false'會在'checkall(this)'旁邊就像這樣'onsubmit =「checkall(this); return false;」'。功能位置也很重要嗎?我還在主要問題中添加了我使用您的示例合併的功能。以防萬一我可能做錯了什麼。 – Thomas

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

希望這有助於!在我的手機上鍵入它可能是一個小的語法錯誤,但邏輯應該讓你找到你想要的!

相關問題