Syed Ali Ahmed
Syed Ali Ahmed

Reputation: 61

Add and Delete Rows from a html table by user input from text box using only javascript

I am trying to make a program using HTML and java-script a program in which user can add content and delete from HTML table what ever row he wants to delete I made it but only one cell is edited by text box and other are not getting the values of there text box please do some help to complete my task as it'll be very appreciated.

My code is:

<!Doctype html PUBLIC "-//W3C//DTD XHTML 1.0 Transitiona//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>

Javascript maybe this my javascript code is not correct written please get any solution for my task

 <script type="text/javascript">

function delrow0()
{
document.getElementById("myTable").deleteRow(0);
}

function displayResult()
{
var table=document.getElementById("myTable");
var row=table.insertRow(0);
var cell1=row.insertCell(0);
var cell2=row.insertCell(1);
var cell3=row.insertCell(2);
cell1.innerHTML=document.getElementById('txtname').value;
cell2.innerHTML=document.getElementById('txtauthor').value;
cell3.innerHTML=document.getElementById('txtcontent').value;

}

</script>
</head>
<body>

HTML

<table id="myTable" border="1">
  <tr>
    <td>cell 1</td>
    <td>cell 2</td>
     <td>cell 3</td>
  </tr>
  <tr>
    <td>cell 4</td>
    <td>cell 5</td>
      <td>cell 6</td>
  </tr>
</table>
<br>
<button type="button" onClick="displayResult()">Insert new row</button>
<button type="button" onClick="delrow0s()">delete</button>

<form name="create">
Name:<input type="text" id="txtname" /><br/>
Author<input type="text" name="txtauthor" /><br/>
CDate:<input type="text" name="txtcdate" /><br/>
CDate:<input type="text" name="txtcontent" style="height:80px; " />
</form>

</body>
</html>

Fiddle here

Upvotes: 1

Views: 3877

Answers (1)

Andrei C
Andrei C

Reputation: 812

your code is fine, just add id attributes to all the inputs and it should run

Name:<input type="text" id="txtname" /><br/>
Author<input type="text" id="txtauthor" name="txtauthor" /><br/>
Date:<input type="text" id="txtcdate" name="txtcdate" /><br/>
Content:<input type="text" id="txtcontent" name="txtcontent" style="height:80px; " />

you should give jQuery a try though, it makes things alot simpler to handle

Upvotes: 3

Related Questions