I want to make a form which takes into values of name, last name, phone num and create contacts inside a list bellow when i click on a button. But problem is its not working, i looked up if it has something to do with forms and tables, but it turns out its most common to wrap up table inside a form to peform some actions with submiting a button. Any ideas to make this more correctly with a form?
HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="style.css" type="text/css">
</head>
<body>
<h1>Enter a new contact</h1>
<table id="table">
<tr>
<td>First name: </td>
<td><input type="text" id="inputName"></td>
</tr>
<tr>
<td>Last name: </td>
<td><input type="text" id="inputLastName"></td>
</tr>
<tr>
<td>Phone number: </td>
<td><input type="text" id="inputPhoneNumber"></td>
</tr>
<tr>
<td></td>
<td><input type="button" value="Submit" onclick="addContact()"></td>
</tr>
</table>
<table class="contactListTable">
<tr>
<td>First name: </td>
<td>Samantha</td>
</tr>
<tr>
<td>Last name: </td>
<td>Doe</td>
</tr>
<tr>
<td>Phone number: </td>
<td>+12345678</td>
</tr>
</table>
<script src="script.js"></script>
</body>
</html>
JS code:
var contactListTable = document.querySelector(".contactListTable");
var nameInput = document.getElementById("inputName");
var lastNameInput = document.getElementById("inputLastName");
var phoneNumber = document.getElementById("inputPhoneNumber");
function addContact() {
// create needed elements
var nameRow = document.createElement("tr");
var firstName = document.createElement("td");
var firstNameValue = document.createElement("td");
var lastNameRow = document.createElement("tr");
var lastName = document.createElement("td");
var lastNameValue = document.createElement("td");
var phoneRow = document.createElement("tr");
var phone = document.createElement("td");
var phoneValue = document.createElement("td");
// append values to created elements
firstName.innerHTML = "First name:";
firstNameValue.innerHTML = nameInput.value;
lastName.innerHTML = "Last name:";
lastNameValue.innerHTML = lastNameInput.value;
phone.innerHTML = "Phone number:";
phoneValue.innerHTML = phoneNumber.value;
// append table datas to table row
nameRow.appendChild(firstName);
nameRow.appendChild(firstNameValue);
lastNameRow.appendChild(lastName);
lastNameRow.appendChild(lastNameValue);
phoneRow.appendChild(phone);
phoneRow.appendChild(phoneValue);
// append table rows to table
contactListTable.appendChild(nameRow);
contactListTable.appendChild(lastNameRow);
contactListTable.appendChild(phoneRow);
};