https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_html_after2
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function afterText() {
$("#tblGrid").html("<td>NameName2</td><td>Budget Value 2</td></tr><tr><td>NameName3</td><td>Budget Value 3</td>");
}
</script>
</head>
<body>
<table>
<tbody>
<th><h4>Name Heading</h4></th>
<th>
<table>
<thead>
<tr>
<th>Budget Heading</th>
</tr>
</thead>
</table>
</th>
<tr id="tblGrid"></tr>
<tr><td>NameName1</td><td>Budget Value 1</td></tr>
</tbody>
</table>
<button onclick="afterText()">Button</button>
</body>
</html>
OUTPUT is something like this after clicking button:
Name Heading Budget Heading
NameName3 Budget Value 3
NameName1 Budget Value 1
Button
Could you help in understanding where is value with number "2" is going?
Output expected:
Name Heading Budget Heading
NameName2 Budget Value 2
NameName3 Budget Value 3
NameName1 Budget Value 1
Button
Also every time we click button, it should not append 2 and 3, but clear old iteration values. Suggestions please!
Your html table structure is slightly incorrect. I have changed the structure of the thead
tag. And you don't need to use the h4
tag for this.
I defined your tr
tag with id=tblGrid as tbody
tag.
Also, you are using the html()
method. But this method overwrites the content. Better use the append()
method.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function afterText() {
$("#tblGrid").append("<tr><td>NameName2</td><td>Budget Value 2</td></tr><tr><td>NameName3</td><td>Budget Value 3</td></tr>");
}
</script>
</head>
<body>
<table>
<thead>
<tr>
<th>Name Heading</th>
<th>Budget Heading</th>
</tr>
</thead>
<tbody id="tblGrid">
<tr>
<td>NameName1</td>
<td>Budget Value 1</td>
</tr>
</tbody>
</table>
<button onclick="afterText()">Button</button>
</body>
</html>