In this video tutorial I’ll demonstrate how to create contact input to submit contact info into JavaScript contact array and how to delete it.
Here is the source code:
<!DOCTYPE html>
<html>
<head>
<title>ZK Tutorials</title>
</head>
<body>
<h1>HTML5 & JavaScript Contact Manager</h1>
<input placeholder="Name" id="name"><br>
<input placeholder="City" id="city"><br>
<button onclick="add()">Add</button>
<div id="contacts"></div>
<script>
var contacts = [];
function add(){
var name = document.getElementById("name").value;
var city = document.getElementById("city").value;
var newContact = {
newName : name,
newCity : city
}
contacts.push(newContact);
updateDiv();
document.getElementById("name").value = "";
document.getElementById("city").value = "";
}
function updateDiv(){
var tempContent = "";
for(var i = 0; i < contacts.length; i++){
tempContent += "<p>Name : " + contacts[i].newName + "<br>City : " + contacts[i].newCity + "<br><span onclick='del(" + i +")'>[del]</span></p>";
}
document.getElementById("contacts").innerHTML = tempContent;
}
function del(i){
contacts.splice(i, 1);
updateDiv();
}
</script>
</body>
</html>