I'm trying to do a basic exercise with JavaScript. The goal of the exercise is to input some values and then show them into a table.
The problem I have is is that when I enter first name as "a", last name as "a" and phone as "6", I get "aa6", instead of "a a 6".
What can I do to fix that?
class clsperson {
constructor(firstName, lastName, celephone) {
this.firstName = firstName;
this.lastName = lastName;
this.celephone = celephone;
}
}
var persons = [];
function addClient() {
var Person = new clsperson(document.getElementById("firstName").value,
document.getElementById("lastName").value, document.getElementById("celephone").value);
persons.push(Person);
document.getElementById("firstName").value = "";
document.getElementById("lastName").value = "";
document.getElementById("celephone").value = "";
}
function viewClients() {
var tblClient = document.getElementById("tblClient");
for (var i = 0; i < persons.length; i++) {
var tr = document.createElement("tr");
tblClient.appendChild(tr);
tr.appendChild(document.createElement("td").appendChild(document.createTextNode(persons[i].firstName)));
tr.appendChild(document.createElement("td").appendChild(document.createTextNode(persons[i].lastName)));
tr.appendChild(document.createElement("td").appendChild(document.createTextNode(persons[i].celephone)));
}
}
<h2>add client into a table</h2>
<table>
<tr>
<td><input id="firstName" type="text" /></td>
<td><input id="lastName" type="text" /></td>
<td><input id="celephone" type="text" /></td>
<td><input id="addClient" type="button" value="add" onclick="addClient()" /></td>
<td><input id="viewClient" type="button" value="show" onclick="viewClients()" /></td>
</tr>
</table>
<table id="tblClient">
<tr>
<th><input type="text" value="first name" /></th>
<th><input type="text" value="last name" /></th>
<th><input type="text" value="celephone" /></th>
</tr>
</table>
appendChildreturns the appended child. So you are appending text nodes to thetr.