There are 2 problems.
In JavaScript for string concatenation you should use the +
operator not .
.
You don't prevent the default action of the event. The page is submitted/refreshed and you don't see the appended element.
$('form').submit(function(event) {
event.preventDefault();
var fname= $('input#form_fname').val();
// ...
$('tr').append('<td>' + fname + '</td>');
});
$('tr').append('<td>' + fname + '</td>');
->>>>>this part is messing up the table. Any idea why?
Your markup is invalid. You should wrap the th
elements with a tr
element. Browsers usually fix the markup. So the $('tr')
element selects the tr
child of the thead
element. You should use a more specific selector for selecting the tr
child of the tbody
element. Something like $('tbody tr')
or $('tr').eq(1)
.
Is there a better option to append this?
I would add empty cells to the tr
element and populate the cells using the input
values.
<table border="1">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email Address</th>
<th>Contact #</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
JavaScript:
$('form').submit(function (event) {
event.preventDefault();
var $td = $('tbody tr td');
$('input', this).each(function (i) {
$td.eq(i).text(this.value);
});
});
https://jsfiddle.net/zbb6fqtc/9/