So I have a table with one row and two columns that creates new rows with info input by the user.
I want to know how to add info into the second column of cells.
The following code adds cells to the first column only:
<!DOCTYPE HTML>
<html>
<body>
Something must be entered here:
<input id="inputName" style="width:100px;"></input>
<button onclick="addRowCell('table1')">Add row</button>
<table id="table1" style="border:1px solid black;">
<tr id="myRow1">
<td>ID</td>
<td>Content 1</td>
</tr>
</table>
<script>
i=1;
function addRowCell(el){
var row = document.getElementById(el);
var fName = document.getElementById("inputName").value;
var x = row.insertRow(i);
x.innerHTML=fName;
i++;
}
</script>
</body>
</html>
JSFiddle for the above: http://jsfiddle.net/tC2zG/
Edit: for anyone with a similar problem - what you see here isn't cells being added, it's rows being added.
You're not adding cells at all, just rows, so add a couple of cells
i = 1;
function addRowCell(el) {
var row = document.getElementById(el);
var fName = document.getElementById("inputName").value;
var x = row.insertRow(i);
var c1 = x.insertCell(0);
var c2 = x.insertCell(1);
c2.innerHTML = fName;
i++;
}
FIDDLE
Update on your JS Fiddle:
i=1;
function addRowCell(el){
var table = document.getElementById(el);
var fName = document.getElementById("inputName").value;
var row = table.insertRow(i);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "ID";
cell2.innerHTML = fName;
i++;
}
Please check if that is the result that you were hoping for.
Related
The function "insert()" makes table cells that contain task names given by input. Every task name has a checkbox appended and how can I inspect if an element in a cell is checked so I can change its properties? I want the function "completeTasks()" to check for a checked element so when I press the button that calls the function, elements that are checked should be green and strikethrough(line-through).
<html>
<head>
</head>
<body>
Task Name: <input type="text" id="name">
<button id="ins" onclick="insert()">Insert</button>
<table id="tabl3">
</table>
<button id="comp" onclick="completeTasks()">Complete Tasks</button>
<button id="del" onclick="deleteTasks()">Delete Tasks</button>
<script type="text/javascript">
var i=0;
var r=0;
var arrName = [];
function insert()
{
var chk = document.createElement("input");
chk.setAttribute("type", "checkbox");
arrName[i] = document.getElementById("name").value;
var table = document.getElementById("tabl3");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
r++;// counting the rows so i can delete them all later if i want to
cell1.innerHTML = arrName[i];
cell1.appendChild(chk); // appending a checkbox to the element so i can check it later
i++;
}
function completeTasks(){
// if one or more elements are checked when clicking this button
// then the checked task name(s) would have green color and have a line-through text decoration.
//.style.color = "green";
//.style.textDecoration = "line-through";
}
function deleteTasks(){
// will probably have to delete all the cells so i did it like this
for(let c = 0; c<r; c++){
document.getElementById("tabl3").deleteRow(0);
}
}
</script>
</body>
</html>
You can first target all the checked check box using Document.querySelectorAll(), then loop through them and set the style to the closest td element.
Demo:
Task Name: <input type="text" id="name">
<button id="ins" onclick="insert()">Insert</button>
<table id="tabl3">
</table>
<button id="comp" onclick="completeTasks()">Complete Tasks</button>
<button id="del" onclick="deleteTasks()">Delete Tasks</button>
<script type="text/javascript">
var i=0;
var r=0;
var arrName = [];
function insert()
{
var chk = document.createElement("input");
chk.setAttribute("type", "checkbox");
arrName[i] = document.getElementById("name").value;
var table = document.getElementById("tabl3");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
r++;// counting the rows so i can delete them all later if i want to
cell1.innerHTML = arrName[i];
cell1.appendChild(chk); // appending a checkbox to the element so i can check it later
i++;
}
function completeTasks(){
var checkedEl = document.querySelectorAll('#tabl3 input:checked'); // get all the checked checkbox inside the table
checkedEl.forEach(function(el){ //loop through them
el.closest('td').style.color = "green";
el.closest('td').style.textDecoration = "line-through";
});
}
function deleteTasks(){
// will probably have to delete all the cells so i did it like this
for(let c = 0; c<r; c++){
document.getElementById("tabl3").deleteRow(0);
}
}
</script>
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>
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 am trying to use JavaScript or ASP C# to add rows to a table in form when the user clicks the add row button. I have working code in JavaScript. I want to add the rows with text input boxes inside of the <td></td> tags. The row count is in my code becasue I am attempting to use it to add IDs to each element for use later.
element.innerHTML(<input id="tagcell"+(rowcount+1)+"" type="text"/>);
function addrow() {
var rowcount =
document.getElementById('tbl').getElementsByTagName('tbody').length;
window.alert(rowcount);
var tableRef = document.getElementById('tbl').getElementsByTagName('tbody')[0];
var newRow = tableRef.insertRow(tableRef.rows.length);
// Insert a cell in the row at index 0
var tagcell = newRow.insertCell(0);
var desccell = newRow.insertCell(1);
var loccell = newRow.insertCell(2);
var Namecell = newRow.insertCell(3);
var Sigcell = newRow.insertCell(4);
tagcell.innerHTML = "";
desccell.innerHTML="";
loccell.innerHTML = "";
Namecell.innerHTML="";
Sigcell.innerHTML = "";
}
<table id=tbl>
<tr>
<td id=tag_no>Col1</td>
<td id=desc> Col2</td>
<td id=loc> col3</td>
<td id=nme> col4</td>
<td id=sig> col5</td>
</tr>
</table>
<input type="button" value="clickme" onclick="addrow()" />
Here's how you could do that. (Obviously you can style the text boxes however you want.) Your code added the rows; I just added a textarea in each cell.
function addrow() {
var tableRef = document.getElementById('tbl').getElementsByTagName('tbody')[0];
var rowcount = tableRef.rows.length;
window.alert(rowcount);
var newRow = tableRef.insertRow(tableRef.rows.length);
var textBox = "<textarea></textarea>";
// Insert a cell in the row at index 0
var tagcell = newRow.insertCell(0);
var desccell = newRow.insertCell(1);
var loccell = newRow.insertCell(2);
var Namecell = newRow.insertCell(3);
var Sigcell = newRow.insertCell(4);
tagcell.innerHTML = textBox;
desccell.innerHTML= textBox;
loccell.innerHTML = textBox;
Namecell.innerHTML= textBox;
Sigcell.innerHTML = textBox;
}
<table id=tbl>
<tr>
<td id=tag_no>Col1</td>
<td id=desc> Col2</td>
<td id=loc> col3</td>
<td id=nme> col4</td>
<td id=sig> col5</td>
</tr>
</table>
<input type="button" value="clickme" onclick="addrow()" />
EDIT: Your row count shows the correct number now. (It was only showing 1 each time before.)
function addrow() {
var myTable = document.querySelector('#tbl');
var row = myTable .insertRow(0);
var cell1 = row.insertCell(0);
cell1.innerHTML = 'My first cell';
// and so on for other cells
}
p.s. please add "" to all your HTML attributes values. For example
<table id="tbl">
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