Mayank Purohit Mayank Purohit - 1 month ago 5
Javascript Question

How to add data to table on click of button using Javascript

<html>
<head>

<style type="text/css">

table, th, td {
position: relative;
border: 1px solid black;
width: 40%;
height:40px;
top: 5%;
}

</style>


<script type="text/javascript">

function lab()
{
var x= document.getElementById('lab').value;
var rows="";
rows+= "<tr><td>"+x+"</td></tr>";

}

function inp()
{
var y= document.getElementById('inp1').value;
}

</script>
</head>
<body>
<button id="lab" onclick="lab()" value="label">Label</button>

<button id="inp1" onclick="inp()" value="Input">Input</button>

<button id="res" onclick="reset()">reset</button>
</body>

<table id="me1">
<tr>
<td></td>
<td></td>
</tr>
<tbody></tbody>

</table>

</html>


enter image description here

I am trying to add the text in the column of the table on the click of the button.

so please help me to add the text written on the button in the column of the table

thank you

Answer

I don't understand your requirement completely, but you can use innerHTML to wipe out earlier contents and insert new. Or use appendChild and createElement to make and insert new elements on the go. The example demonstrates both with each button.

function lab() {
  var x = document.getElementById('lab').value;
  var rows = "";
  rows += "<tbody><tr><td>" + x + "</td></tr></tbody>";
  document.getElementById('me1').innerHTML = rows;

}

function inp() {
  var table = document.getElementById('me1');
  var tbody = table.getElementsByTagName('tbody')[0];
  var y = document.getElementById('inp1').value;
  var text = document.createTextNode(y);
  var col = document.createElement('td');
  var row = document.createElement('tr');
  col.appendChild(text);
  row.appendChild(col);
  tbody.appendChild(row);
}
table,
th,
td {
  position: relative;
  border: 1px solid black;
  width: 40%;
  height: 40px;
  top: 5%;
}
<button id="lab" onclick="lab()" value="label">Label</button>

<button id="inp1" onclick="inp()" value="Input">Input</button>

<button id="res" onclick="reset()">reset</button>
</body>

<table id="me1">
  <tr>
    <td></td>
    <td></td>
  </tr>
  <tbody></tbody>

</table>

Comments