I have JSON data that is displayed in an HTML table. I have separate input fields like the same keys in the object(firstname, lastname, email, phone number) and an "Add Row" Button.
I need to enter values in the input fields and then when I click the "Add Row" button the Input field should be appended to the table.
I can display the data in the table but I am not able to append the new data to the table. I also need to validate the fields. Can anyone help to solve this?
var obj=[{Firstname:"Bob",Lastname:"Mayer",Email:"[email protected]",Number: "123456789"}, {Firstname:"Steven",Lastname:"Spil",Email:"[email protected]",Number: "987654321"}, {Firstname:"Paul",Lastname:"Taucker",Email:"[email protected]",Number: "578954321"}];
var form = document.createElement('form');
document.body.appendChild(form);
var table = document.createElement("table");
table.setAttribute("id", "myTable");
form.appendChild(table);
var row = document.createElement("tr");
table.appendChild(row);
Object.keys(obj[0]).forEach(function(val) {
var cell = document.createElement("th");
row.appendChild(cell);
cell.innerHTML = "Sl.No";
cell.innerHTML = val;
cell.style.border = '1px solid #ccc';
});
for (var i = 0; i < obj.length; i++) {
var row = document.createElement("tr");
table.appendChild(row);
for (key in obj[i]) {
var cell = document.createElement("td");
row.appendChild(cell);
cell.innerHTML = obj[i][key];
cell.style.border = '1px solid #ccc';
}
}
var addForm = document.createElement('div');
form.appendChild(addForm);
var checkbox = document.createElement('input');
checkbox.type = "checkbox";
var input = document.createElement('input');
input.type = "text";
input.id = "firstName";
input.placeholder = "Firstname";
addForm.appendChild(input);
var input1 = document.createElement('input');
input1.type = "text";
input.id = "lastName";
input1.placeholder = "Lastname";
addForm.appendChild(input1);
var input2 = document.createElement('input');
input2.type = "email";
input.id = "emailId";
input2.placeholder = "Email";
addForm.appendChild(input2);
var input3 = document.createElement('input');
input3.type = "number";
input.id = "phNum";
input3.placeholder = "Number";
addForm.appendChild(input3);
var btnSave = document.createElement('button');
btnSave.innerHTML = "Save";
var btnEdit = document.createElement('button');
btnEdit.innerHTML = "Edit";
var btnClick = document.createElement('input');
btnClick.type = "button";
btnClick.value = "Add Row";
btnClick.onclick = addTable;
form.appendChild(btnClick);
var addTable = function() {
var fn = document.getElementById("firstName").value;
var ln = document.getElementById("lastName").value;
var mail = document.getElementById("emailId").value;
var num = document.getElementById("phNum").value;
};