GDAYHTML表單提交 - 添加輸入VALES的JavaScript陣列
林創建
目前粘在接觸的創建一個JavaScript /打字稿應用程序,可以創建和編輯聯繫人 - 請查看下面的代碼。我創建了一個名爲「createContact」的函數來驗證用戶的輸入。然後通過有效的信息 「的addContact」
//mock data to fill array
let peter = {
firstName: "Peter",
lastName: "Best",
companyName: "Industrie Clothing",
phoneNumber: "0435 000 000",
email: "[email protected]",
postalAddress: "7 Myco Court"
};
//storing the mock data in an array
let contacts = [peter];
// sending to the console - troubleshooting
function printPerson(person):void {
let li = document.createElement("li");
let node = document.createTextNode(person.firstName+" "+person.lastName +" "+ person.phoneNumber);
li.appendChild(node);
let elt = document.getElementById("contactList");
elt.appendChild(li);
}
//this function is used to loop through ALL contacts
function list():void{
var contactsLength = contacts.length;
for (var i = 0; i < contactsLength; i++) {
printPerson(contacts[i]);
}
}
// function to "add" a contact into the contacts array
function addContact(firstName: string, lastName: string, companyName: string, email: string, phoneNumber: string, postalAddress: string):void{
let object = {
firstName: firstName,
lastName: lastName,
companyName: companyName,
email: email,
phoneNumber: phoneNumber,
postalAddress: postalAddress
};
contacts[contacts.length] = object;
};
function createContact():void{
let firstName = <HTMLInputElement>document.getElementById("firstName");
let surname = <HTMLInputElement>document.getElementById("surname");
let phoneNumber = <HTMLInputElement>document.getElementById("phoneNumber");
let email = <HTMLInputElement>document.getElementById("email");
let companyName = <HTMLInputElement>document.getElementById("companyName");
let postalAddress = <HTMLInputElement>document.getElementById("postalAddress");
if((email.value == "") || (phoneNumber.value == "")){
alert("Please Provide Either An Email or Phone Number");
}
else {
alert("ALL GOOD");
addContact(firstName, surname, phoneNumber, companyName, email, postalAddress);
}
}
addContact("tim", "tom", "google", "[email protected]", "0436 139 648", "home is where the heart is");
//displaying contacts
list();
HTML
<div class="content">
<div id="createContact">
First name:<br>
<input type="text" id="firstName" name="firstName">
<br>
Last name:<br>
<input type="text" id="lastName" name="lastName" required>
<br>
Company Name:<br>
<input type="text" id="companyName" name="companyName">
<br>
Email:<br>
<input type="email" id="email" name="email">
<br>
Phone Number:<br>
<input type="text" id="phoneNumber" name="phoneNumber">
<br>
Postal Address:<br>
<input type="text" id="postalAddress" name="postalAddress">
<br><br>
<button onClick = "createContact()">Submit</button>
</div>
</div>
讓我知道,我的問題是什麼!
謝謝
我們不介意讀者。你還沒有告訴我們你的代碼有什麼錯誤/問題。 – Webeng
我認爲在createContact函數中的addContact調用中的firstName ...必須是firstName.value ... –
@Webeng目前,「addContact」函數什麼也不做,它不會將聯繫人添加到數組中。 – peterbest69