I have a table of rows and a button to delete it in each row.
I can remove a row bot the problem is that I need to update the value deleteRow(nb_of_rows) in every time I remove a row
This is the table code in HTML
<input type="button" id="insert_row" value="Insert Row" onclick="insert_row()" >
<br><br>
<table id="mytable" width="100%" border="2" >
<tr>
<th>Sr.</th>
<th>Item Name</th>
<th>Price</th>
<th>Count</th>
<th>Total</th>
<th>Delete</th>
</tr>
</table>
and this is JavaScript code
var srn = 0;
function insert_row(){
var table = document.getElementById("mytable")
var nb_of_rows = document.getElementById("mytable").rows.length;
var row = table.insertRow(nb_of_rows);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
cell1.innerHTML = changeSR();
var delete_btn = document.createElement("input");
delete_btn.type = "button";
delete_btn.className = "btn";
delete_btn.value = "Delete";
cell6.appendChild(delete_btn);
delete_btn.onclick = function deleteRow(){
return document.getElementById("mytable").deleteRow(nb_of_rows);
}
}
function changeSR(){
return srn = srn + 1 ;
}
and this is an online share of my code
enter link description here
The issue occurs because the index in nb_of_rows is in danger of being out of date by the time the button is clicked (especially if other rows and have been added and deleted in the meantime). Therefore it will either delete the wrong row, or crash because the index doesn't exist in the table any more.
The solution is fairly simple: make the button get the parent row it belongs to, and then get that row's current index at the point of deletion, rather than relying on the index it had when it was added.
Usefully the row element has an index property telling you its current index in the table body, which makes this solution possible.
Here's the event code you need:
delete_btn.onclick = function deleteRow() {
var row = this.parentElement.parentElement; //get the parent of the parent (i.e. the first parent is the table cell, and the parent of that is the row)
document.getElementById("mytable").deleteRow(row.rowIndex);
}
(BTW it makes no sense really to have a return statement in an event handler, since the control returns to somewhere in the JS event-handling engine, not to your code, so I removed that at the same time.)
Demo:
var srn = 0;
function insert_row() {
var table = document.getElementById("mytable")
var nb_of_rows = document.getElementById("mytable").rows.length;
var row = table.insertRow(nb_of_rows);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
var cell6 = row.insertCell(5);
cell1.innerHTML = changeSR();
var delete_btn = document.createElement("input");
delete_btn.type = "button";
delete_btn.className = "btn";
delete_btn.value = "Delete";
cell6.appendChild(delete_btn);
delete_btn.onclick = function deleteRow() {
var row = this.parentElement.parentElement;
document.getElementById("mytable").deleteRow(row.rowIndex);
}
}
function changeSR() {
return srn = srn + 1;
}
<input type="button" id="insert_row" value="Insert Row" onclick="insert_row()">
<br><br>
<table id="mytable" width="100%" border="2">
<tr>
<th>Sr.</th>
<th>Item Name</th>
<th>Price</th>
<th>Count</th>
<th>Total</th>
<th>Delete</th>
</tr>
</table>
Related
I'm trying to assign an unique id to each row to then modify rows with specific number id's. However since the function is called every time on button click, I always get the same output for the number.
Here is my JavaScript Function
[<script type="text/javascript">
function insert_row(){
var firstName = document.getElementById('first_name').value;
var lastName = document.getElementById('last_name').value;
var human = "human";
var id =1;
var table = document.getElementById("saving_table");
// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(1);
row.id=id;
var rowId = row.id;
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
// Add some text to the new cells:
cell1.innerHTML = firstName;
cell2.innerHTML = lastName;
cell3.innerHTML = human+ rowId.toString();
id++;
}
</script>][1]
Here is my table declaration
<div class="container">
<table class="table table-bordered" id="saving_table">
<caption>Classmates</caption>
<thead>
<tr>
<th>FirstName</th>
<th>LastName</th>
<th>Human or Vampire?</th>
</tr>
</thead>
</table>
<button class="btn btn-primary" onclick="insert_row()">Submit</button>
and an image of my output just incase:
Basically you just need to move the id variable outside of the function. That way it's only set to 1 when your code loads, and then each function call increments it.
// global
var id = 1;
function insert_row() {
// ...
demo
// global
var id = 1;
function insert_row() {
var firstName = document.getElementById('first_name').value;
var lastName = document.getElementById('last_name').value;
var human = "human";
var table = document.getElementById("saving_table");
// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(1);
row.id = id;
var rowId = row.id;
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
// Add some text to the new cells:
cell1.innerHTML = firstName;
cell2.innerHTML = lastName;
cell3.innerHTML = human + rowId.toString();
id++;
}
<div class="container">
<table class="table table-bordered" id="saving_table">
<caption>Classmates</caption>
<thead>
<tr>
<th>FirstName</th>
<th>LastName</th>
<th>Human or Vampire?</th>
</tr>
</thead>
</table>
<input id="first_name" />
<input id="last_name" />
<button class="btn btn-primary" onclick="insert_row()">Submit</button>
</div>
Since the id variable is being initialized in each function call, all the rows end up having the same id(that is, 1). One of the ways of solving this would be to simply place the var id = 1; declaration before the start of function insert_row() as a global variable.
However, in order to avoid using global variables, we could get the count of all the existing rows of the table and add 1 to it to get the new id in the following manner:
[<script type="text/javascript">
function insert_row(){
var firstName = document.getElementById('first_name').value;
var lastName = document.getElementById('last_name').value;
var human = "human";
var table = document.getElementById("saving_table");
// get count of the number of rows that already exist
var rowCount = table.getElementsByTagName("tr").length;
var id = rowCount + 1;
// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(id);
row.id=id;
var rowId = row.id;
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
// Add some text to the new cells:
cell1.innerHTML = firstName;
cell2.innerHTML = lastName;
cell3.innerHTML = human+ rowId.toString();
id++;
}
][1]
The HTML code would remain the same. In case your application is large or is headed towards being a large project, I'd strongly recommend using the second method instead of defining a global variable. Global variables tend to get very difficult to manage as the application size grows.
Please, make better code:
1) increase insertRow for each new line
2) don't repeat all document.getElementById for each call
3) don't mix html code with JS ( onclick="insert_row()" )
4) If you made a TABLE with THEAD, use TBODY
const
in_firstName = document.getElementById('first_name'),
in_lastName = document.getElementById('last_name'),
human_str = "human",
tableBody = document.querySelector('#saving_table tbody')
;
var Table_Row_ID = 0;
document.getElementById('insert-row').onclick = function()
{
// Create an empty <tr> element and add it to the 1st position of the table:
let row = tableBody.insertRow(Table_Row_ID);
row.id = ++Table_Row_ID;
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
let
cell1 = row.insertCell(0),
cell2 = row.insertCell(1),
cell3 = row.insertCell(2)
;
// Add some text to the new cells:
cell1.textContent = in_firstName.value;
cell2.textContent = in_lastName.value;
cell3.textContent = human_str + row.id;
}
<div class="container">
<table class="table table-bordered" id="saving_table">
<caption>Classmates</caption>
<thead>
<tr>
<th>FirstName</th>
<th>LastName</th>
<th>Human or Vampire?</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div class="container">
<input type="text" id="first_name" placeholder="first_name" />
<input type="text" id="last_name" placeholder="last_name" />
<button class="btn btn-primary" id="insert-row">Add Row</button>
</div>
Declare the counter outside of function.
Demo
Details commented in demo
// Reference tags
var btn = document.querySelector('button');
var first = document.getElementById('firstName');
var last = document.getElementById('lastName');
var spec = document.getElementById('species');
// Declare counter
var i = 0;
function insert_row(e) {
// Reference <tbody> (Not <table>)
var table = document.querySelector("tbody");
// Insert <tr> (No index is needed)
var row = table.insertRow();
// Add ID to <tr>
row.id = 'r' + i;
// for every loop...
for (let c = 0; c < 3; c++) {
// ...insert a <td>...
var cell = row.insertCell(c);
// ...1st loop add the value of first name input as text...
if (c === 0) {
cell.textContent = first.value;
// ...2nd loop add the value of last name input as text...
} else if (c === 1) {
cell.textContent = last.value;
// ...3rd loop add the value of species select as text...
} else if (c === 2) {
cell.textContent = spec.value;
// ...otherwise just end loop
} else {
break;
}
}
// Increment counter
i++;
}
// Add click event handler to button
btn.onclick = insert_row;
table {
table-layout: fixed;
width: 75%;
margin: 10px auto;
}
th {
width: 33%
}
td {
text-align: center
}
caption {
font-size: 1.2rem;
font-weight: 900;
}
input,
select,
button {
display: inline-block;
font: inherit;
height: 3ex;
line-height: 3ex;
vertical-align: middle;
}
select,
button {
height: 4ex;
}
button {
float: right
}
<div class="container">
<table class="table table-bordered" id="saving_table">
<caption>Classmates</caption>
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Species</th>
</tr>
</thead>
<tbody></tbody>
</table>
<input id='firstName' placeholder='First'>
<input id='lastName' placeholder='Last'>
<select id='species'>
<option value=''>Species</option>
<option value='Human 🕵'>Human 🕵</option>
<option value='Vampire 🧛'>Vampire 🧛</option>
</select>
<button class="btn btn-primary">Submit</button>
</div>
I want to add new row, and remove previously added row with an onclick event.
I write code for it but this code only insert rows not delete previous one.
js
function addRow(tableID) {
console.log('hi')
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount + 1;
var cell3 = row.insertCell(2);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "txtbox[]";
cell3.appendChild(element2);
}
html
<input type="button" value="Add Row" onclick="addRow('dataTable')" />
<table id="dataTable" border="1">
<tr>
</tr>
</table>
Use deleteRow().. and you might just be able to do it.
function addRow(tableID) {
console.log('hi')
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if(rowCount) {
table.deleteRow(-1);
}
...
}
I am writing a code in HTML + Jquery and need to add rows to a table dynamically.
I've written the code to add the rows dynamically, but it doesn't seem to work.
Here is my JScript code :
<script language="JavaScript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "date";
element1.name="datebox[];
element1.id = "dt";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount + 1;
var element2 = document.createElement("input");
element2.type = "select";
element2.name = "selectbox[]";
element2.id = "slct";
cell2.appendChild(element2);
var cell3 = row.insertCell(2);
cell3.innerHTML = rowCount + 1;
var element3 = document.createElement("input");
element3.type = "text";
element3.name = "txtbox[]";
element3.id = "txt";
cell3.appendChild(element3);
table.appendChild(cell1);
}
</script>
This is my Table:
<table id = "tab" style="width:500px">
<tr>
<th>Date</th>
<th>Treatment Goal</th>
<th>Comment</th>
</tr>
<tr>
<td><INPUT type="date" name="datebox[]" id = "dt"/></td>
<td>
<SELECT name="selectbox[]" id = "slct">
</SELECT>
</td>
<td><INPUT type="text" name="txtbox[]" id = "txt"/></td>
</tr>
</table>
I am calling the function in the onClick event of a button like this :
<input type="button" id="add" value="+" name="Add" onclick="addRow('tab')"/>
The html page doesn't respond to the click event and nothing happens.
Cannot understand what's going wrong.
Working Fiddle
The first problem is a syntax error on this line (you didn't close the double quote):
element1.name="datebox[];
^ missing "
The second problem is you are appending the cell to the table which is wrong, you should be appending the row:
table.appendChild(row);
^ changed to row from cell
You are missing a quotation mark on the line:
element1.name="datebox[];
after the name element.
I have a HTML table and i can add a new row to that table using javascript.
I want to call a javascript (Ajax) function using the onchange event for each of the cells on the table.
`
<script type="text/javascript" src="nextTest.js"></script>
<SCRIPT language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
cell1.innerHTML = rowCount + 1;
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "txtbox[]";
element2.onchange = nexttest();
cell2.appendChild(element2);
}
</SCRIPT>
</HEAD>
<body>
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<TABLE id="dataTable" width="350px" border="1">
<TR>
<TD> 1 </TD>
<TD> <INPUT type="text" /> </TD>
</TR>
</TABLE>
</body>
</html>`
When i press the button, a new row is added and the onchange event is fired.
What i want to do is when ever someone enters data into those new cells, i want the onchange event to fire. The event is called 'nextTest' and it is stored in an external file.
When i insert the new row, the event fires, but if i update one of the cells, nothing happens.
What am i doing wrong?
Thanks in advance
you must assign a function, not a function-call(except the called function returns another function).
Omit the parentheses:
element2.onchange = nexttest;
function nexttest(evt){
alert(evt.target.value);
}
function addRow (tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
cell1.innerHTML = rowCount + 1;
var cell2 = row.insertCell(1);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "txtbox[]";
element2.onchange = nexttest; // give a valid function identifier here .
cell2.appendChild(element2);
}
http://jsbin.com/iropam/2/edit
I am trying to display a table with data in runtime using script.
I called the script from table header. Is that possible to call a function from table header.
</HEAD>
<BODY>
<TABLE id="dataTable" width="350px" border="1" onload="start('dataTable');">
<TR>
<THEAD>
<TR>
<TH>Select</TH>
<TH>Id</TH>
<TH>Name</TH>
<TH>Age</TH>
<TH>Dept</TH>
<TH>Option</TH>
</TR>
</THEAD>
</TABLE>
</BODY>
</HTML>
The Script is
function start(dataTable) {
var data = new Array();
var id;
var name;
var age;
var dept;
data[0].id = "1";
data[0].name = "Tamil";
data[0].age = "23";
data[0].dept = "CSE";
data[1].id = "1";
data[1].name = "Tamil";
data[1].age = "23";
data[1].dept = "CSE";
data[2].id = "1";
data[2].name = "Tamil";
data[2].age = "23";
data[2].dept = "CSE";
for (var i = 0; i<data.length; i++)
{
var table = document.getElementById(tableID);
var rowCount = data.length;
var row = table.insertRow(rowCount);
//Check box
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
cell1.appendChild(element1);
//ID Column
var cell2 = row.insertCell(2);
cell2.innerText = data[i].id;
//Name Column
var cell3 = row.insertCell(3);
cell3.innerText = data[i].name;
//Age Column
var cell4 = row.insertCell(4);
cell3.innerText = data[i].age;
//Dept Column
var cell5 = row.insertCell(5);
cell5.innerText = data[i].dept;
//Button Column
var cell6 = row.insertCell(6);
var element2 = document.createElement("input");
element2.setAttribute("type", "button");
element2.setAttribute("id", "dataRow"+id);
element2.setAttribute("value", "Edit");
cell6.appendChild("element2");
}
}
The output is just the Headers. I cant get the data into table.
Thanks for suggestions in advance.
width="350px"
px is CSS. No px when using the HTML attribute.
onload="start('dataTable');"
There is no load event on <table>, this will never be called. Put a <script> element after the table to call the function.
var data = new Array();
For sanity, use [] array literal syntax:
var data= [
{id: 1, name: 'Tamil', age: 23, dept: 'CSE'},
...
];
var id; [and name etc.]
You never use these variables. Declaring vars has nothing to do with members of an object.
document.getElementById(tableID)
You called that variable dataTable not tableID.
cell2.innerText = data[i].id;
innerText is a non-standard IE extension. Consider using the standard textContent property first, if available, or just use plain old cell2.appendChild(document.createTextNode(data[i].id));, which is supported more widely than either.
element2.setAttribute("type", "button");
Never use getAttribute/setAttribute in an HTML document, there are bugs in it in IE. Instead use the DOM Level 2 HTML properties, which are easier to read anyway. element2.type= 'button';.
cell6.appendChild("element2");
That's a string, not the variable element2.
Just call your script in a <script> tag after </table>. Your script should be able to see the table elements because they're alreadyy loaded