Javascript Add Table Row - javascript

I'm not sure how to add a row where I want it.
<script language="javascript">
var i = 1;
function changeIt()
{
i++;
my_div.innerHTML = my_div.innerHTML +"<tr><td valign='middle'><strong>URL "+ i+":</strong></td><td><input name='url'+ i type='text' size='40' /></td></tr>"
}
</script>
<form method="post" action="<?php echo $_SERVER["REQUEST_URI"]; ?>">
<table width="300px">
<tr>
<td valign="middle"><strong>Name:</strong></td>
<td><input name="name" type="text" size="40" /></td>
</tr>
<tr>
<td valign="middle"><strong>Password:</strong></td>
<td><input name="password" type="text" size="40" /></td>
</tr>
<tr>
<td valign="middle"><strong>URL:</strong></td>
<td><input name="url" type="text" size="40" />+</td>
</tr>
<tr id="my_div"></tr>
<tr>
<td valign="middle"><strong>ETC:</strong></td>
<td><input name="etc" type="text" size="40" /></td>
</tr>
The following is where I want the rows to appear:
<tr id="my_div"></tr>
Currently that produces new rows within a row. I don't want that. I only want a new row not in a row.
When I click the + I want it to produce:
<tr>
<td valign="middle"><strong>URL 2:</strong></td>
<td><input name="url2" type="text" size="40" /></td>
</tr>
I don't want that within:
<tr id="my_div"></tr>
I just have that there because I don't know what to do.

Don't use innerHTML to modify tables, it will throw an error in most versions of IE. Use DOM methods.
Don't use an A element when you don't want an link or anchor, use an element like a button or styled span.
You can't add a TR element as a child of a DIV element, it's invalid. You must add it as a child of a table section element (thead, tbody or tfoot). In some cases you can add rows to a table element but some browsers don't like that either.
So to create the new row, use:
var tr = document.createElement('tr');
var td = tr.appendChild(document.createElement('td'));
// Much better to add a class and do this stuff with CSS
td.style.valign = 'middle';
var span = document.createElement('span');
span.style.fontWeight = 'bold';
span.appendChild(docment.createTextNode('URL ' + i);
td = tr.appendChild(document.createElement('td'));
var input = td.appendChild(document.createElement('input'));
input.name = 'url' + i;
input.type = 'text';
input.size = '40'
now append the TR to a table section somewhere.
document.getElementById('myTable').tBodies[0].appendChild(tr);
The whole thing looks like:
<script>
var i = 1;
function changeIt() {
var tr = document.createElement('tr');
var td = tr.appendChild(document.createElement('td'));
td.style.valign = 'middle';
var span = td.appendChild(document.createElement('span'));
span.style.fontWeight = 'bold';
span.appendChild(document.createTextNode('URL ' + i));
td = tr.appendChild(document.createElement('td'));
var input = td.appendChild(document.createElement('input'));
input.name = 'url' + ++i;
input.type = 'text';
input.size = '40'
document.getElementById('myTable').tBodies[0].appendChild(tr);
}
</script>
<form>
<table width="300px">
<tr>
<td valign="middle"><strong>Name:</strong></td>
<td><input name="name" type="text" size="40" /></td>
</tr>
<tr>
<td valign="middle"><strong>Password:</strong></td>
<td><input name="password" type="text" size="40" /></td>
</tr>
<tr>
<td valign="middle"><strong>URL:</strong></td>
<td><input name="url" type="text" size="40">
<input type="button" onclick="changeIt();" value="+"></td>
</tr>
<tr id="my_div"></tr>
<tr>
<td valign="middle"><strong>ETC:</strong></td>
<td><input name="etc" type="text" size="40" /></td>
</tr>
</table>
</form>
<table id="myTable">
<tbody></tbody>
</table>
You could build the row to add in the bottom table and have it hidden, then just clone it and modify the bits that need it.

Ok, so to add another row to the table after URL1, give the row before, URL1, an id attribute then append to the innerHTML. I set the JS to retrive the current URL number, starting with 1, so that each time you click the button, it appends a URL row.
I also updated your name attribute to include the '' ticks
<script language="javascript">
var i = 1;
function changeIt(){
var myCurrentTable = document.getElementById("myTable");
var txt = myCurrentTable.innerHTML;
i++;
txt = txt.replace('<tr id="etc_row">', '</tr><tr id="url_row_' + i + '"><td valign="middle"><strong>URL '+ i+':</strong></td><td><input name="url' + i + '" type="text" size="40" /></td><tr id="etc_row">');
myCurrentTable.innerHTML = txt;
}
</script>
<form method="post" action="<?php echo $_SERVER["REQUEST_URI"]; ?>">
<table id="myTable" width="300px">
<tr id="name_row">
<td valign="middle"><strong>Name:</strong></td>
<td><input name="name" type="text" size="40" /></td>
</tr>
<tr id="pw_row">
<td valign="middle"><strong>Password:</strong></td>
<td><input name="password" type="text" size="40" /></td>
</tr>
<tr id="url_row_1" >
<td valign="middle"><strong>URL:</strong></td>
<td><input name="url" type="text" size="40" />+</td>
</tr>
<tr id="etc_row">
<td valign="middle"><strong>ETC:</strong></td>
<td><input name="etc" type="text" size="40" /></td>
</tr>
</table>

Related

Add row and td element and a checkbox in the table

I have the following table structure
<form method=POST class='form leftLabels'>
<table >
<tr >
<th >Code:</th>
<td ><input type='text' name='f[id]' size='60' value='10' /></td>
</tr>
<tr ><th >Name:</th>
<td ><input type='text' name='f[name]' size='60' value='Aa' /></td>
</tr>
// <<<< Here I would like to add a row
<tr >
<td class=' nogrid buttonsClass'><button type=submit>Save</button>
</td>
</tr>
</table>
</form>
The row that I am trying to add should have the following html:
<tr>
<th> Delete the record?</th>
<td><input type='checbox' name='delete' value=1></td>
</tr>
I have the following Javascript / jQuery code:
var trCnt=0;
$('table tr').each(function(){
trCnt++;
});
rowToInsertCheckbox = trCnt - 1;
$('table').after(rowToInsertCheckbox).append(
$(document.createElement('tr')),
$(document.createElement('td').html('Delete the record'),
$(document.createElement('td').html('Checkbox here?')),
);
which does find the right row after which the insert should be done, but the code does not work.
after() adds the new content after the target element, but outside it. tr need to be inside the table. In addition you need to append the td to the tr, not the table.
To place the new tr in your target position you can select the last tr in the table and use insertBefore(), like this:
let $newRow = $('<tr />').insertBefore('table tr:last');
$('<td>Delete the record?</td>').appendTo($newRow);
$('<td><input type="checkbox" name="delete" value="1"></td>').appendTo($newRow);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST" class="form leftLabels">
<table>
<tr>
<th>Code:</th>
<td><input type="text" name="f[id]" size="60" value="10" /></td>
</tr>
<tr>
<th>Name:</th>
<td><input type="text" name="f[name]" size="60" value="Aa" /></td>
</tr>
<tr>
<td class="nogrid buttonsClass"><button type="submit">Save</button></td>
</tr>
</table>
</form>
One way to locate the row after which the content should be added is:
var tr = $("th").filter(function () {
return $(this).text() == "Name:";
}).closest("tr");
Then add the row:
$(tr).after("<tr><th> Delete the record?</th><td><input type='checkbox' name='delete' value=1></td></tr>");
$(document).ready(function() {
var tr = $("th").filter(function() {
return $(this).text() == "Name:";
}).closest("tr");
$(tr).after("<tr><th>Delete the record?</th>" +
"<td><input type='checkbox' name='delete' value=1></td>" +
"</tr>");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method=POST class='form leftLabels'>
<table>
<tr>
<th>Code:</th>
<td><input type='text' name='f[id]' size='60' value='10' /></td>
</tr>
<tr>
<th>Name:</th>
<td><input type='text' name='f[name]' size='60' value='Aa' /></td>
</tr>
<tr>
<td class=' nogrid buttonsClass'><button type=submit>Save</button>
</td>
</tr>
</table>
</form>

how to add array values in text box

I have three text box that given as an array, I want to add two text box and get a result in the third text box as shown in below.
<tbody>
<?php
$i=1;
foreach ($sub as $row)
{
?>
<tr>
<td><?php echo $i++;?>
</td>
<td> <div><span style="border: none;"><input type="text" name="subject[]" class="textbox" value="<?php echo $row->subject_name;?>"></span></div></td>
<td><input type="text" name="mark-1[]" value="" id="mark1"></td>
<td><input type="text" name="mark-2[]" value="" id="mark2"></td>
<td><input type="text" name="total-mark[]" value="" id="totmark" onclick="add_number()"></td>
</tr>
<?php } ?>
<tr>
<th colspan="4">Total Mark</th>
<td></td></tr>
</tbody>
i have used the below script and its running but getting a result in the first loop
<script type="text/javascript">
function add_number() {
var first_number = parseInt(document.getElementById("mark1").value);
var second_number = parseInt(document.getElementById("mark2").value);
var result = first_number + second_number;
document.getElementById("totmark").value = result;
}
</script>
please help us get an answer
html
<tbody>
<?php
$i=1;
$k=1;
foreach ($sub as $row)
{ $k++;
?>
<tr>
<td><?php echo $i++;?>
</td>
<td> <div><span style="border: none;"><input type="text" name="subject[]" class="textbox" value="<?php echo $row->subject_name;?>"></span></div></td>
<td><input type="text" name="mark-1[]" value="" id="mark1-<?php echo $k;?>"></td>
<td><input type="text" name="mark-2[]" value="" id="mark2-<?php echo $k;?>"></td>
<td><input type="text" name="total-mark[]" value="" id="totmark-<?php echo $k;?>" onclick="add_number(<?php echo $k;?>)"></td>
</tr>
<?php } ?>
<tr>
<th colspan="4">Total Mark</th>
<td></td></tr>
</tbody>
Script
<script type="text/javascript">
function add_number(k) {
var first_number = parseInt(document.getElementById("mark1-"+k).value);
var second_number = parseInt(document.getElementById("mark2-"+k).value);
var result = first_number + second_number;
document.getElementById("totmark-"+k).value = result;
}
</script>
The problem is the repeated IDs for each iteration, mark1, mar2, mark1, mark2, and so on. The function getElementById is returning the first element.
An alternative is to use the function closest('tr') and then find by name [name="mark-1[]"] and [name="mark-2[]"]. Then find the field to store the result using this .querySelector('[name="total-mark[]"]').
Finally, using the function addEventListener you can bind the event click to the whole set of elements [name="total-mark[]"].
document.querySelectorAll('[name="total-mark[]"]').forEach(function(elem) {
elem.addEventListener('click', add_number);
});
function add_number() {
var tr = this.closest('tr');
var first_number = tr.querySelector('[name="mark-1[]"]').value;
var second_number = tr.querySelector('[name="mark-2[]"]').value;
var result = Number(first_number) + Number(second_number);
this.value = result;
}
<table>
<tbody>
<tr>
<td><input type="text" name="mark-1[]" value="" ></td>
<td><input type="text" name="mark-2[]" value="" ></td>
<td><input type="text" name="total-mark[]" value="" placeholder='click to totalize'></td>
</tr>
<tr>
<td><input type="text" name="mark-1[]" value="" ></td>
<td><input type="text" name="mark-2[]" value="" ></td>
<td><input type="text" name="total-mark[]" value="" placeholder='click to totalize'></td>
</tr>
</tbody>
</table>
A recommendation is using the current index from the PHP variable $i and add specific IDs to every field, that way you will be able to get the elements directly. For example, the two fields would have these IDs: mark-1-1[], mark-1-2[] and mark-2-1[], mark-2-2[], and so on.
This approach uses the attribute dataset.
document.querySelectorAll('[name="total-mark[]"]').forEach(function(elem) {
elem.addEventListener('click', add_number);
});
function add_number() {
var field = this.dataset.field;
var first_number = document.getElementById('mark-1-' + field + '[]').value;
var second_number = document.getElementById('mark-2-' + field + '[]').value;
var result = Number(first_number) + Number(second_number);
this.value = result;
}
<table>
<tbody>
<tr>
<td><input type="text" id="mark-1-1[]" value="" ></td>
<td><input type="text" id="mark-2-1[]" value="" ></td>
<td><input type="text" data-field='1' name="total-mark[]" value="" placeholder='click to totalize'></td>
</tr>
<tr>
<td><input type="text" id="mark-1-2[]" value="" ></td>
<td><input type="text" id="mark-2-2[]" value="" ></td>
<td><input type="text" data-field='2' name="total-mark[]" value="" placeholder='click to totalize'></td>
</tr>
</tbody>
</table>

Dynamically add/remove rows from html table

I am working on a table that can be modified by pressing "Delete" buttons in each row and "Insert row" to add a new one at the end:
So far by now my code is:
<!DOCTYPE html>
<html>
<head>
<script>
function deleteRow(id,row) {
document.getElementById(id).deleteRow(row);
}
function insRow(id) {
var filas = document.getElementById("myTable").rows.length;
var x = document.getElementById(id).insertRow(filas);
var y = x.insertCell(0);
var z = x.insertCell(1);
y.innerHTML = '<input type="text" id="fname">';
z.innerHTML ='<button id="btn" name="btn" > Delete</button>';
}
</script>
</head>
<body>
<table id="myTable" style="border: 1px solid black">
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="deleteRow('myTable',0)"></td>
</tr>
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="deleteRow('myTable',1)"></td>
</tr>
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="deleteRow('myTable',2)"></td>
</tr>
</table>
<p>
<input type="button" onclick="insRow('myTable')" value="Insert row">
</p>
</body>
</html>
But i cannot attach the function onclick="deleteRow('myTable',0)" on
z.innerHTML ='<button id="btn" name="btn"> Delete</button>'
¿Is there something else i need to declare in order to make that button work when clicked?
Thanks for your answers
First off, IDs must be unique, so why not use classes here instead?
Second, if you're using jQuery, then use jQuery.
Third, you need to use event delegation when dynamically adding elements, so try the following:
$('#myTable').on('click', 'input[type="button"]', function () {
$(this).closest('tr').remove();
})
$('p input[type="button"]').click(function () {
$('#myTable').append('<tr><td><input type="text" class="fname" /></td><td><input type="button" value="Delete" /></td></tr>')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="myTable" style="border: 1px solid black">
<tr>
<td>
<input type="text" class="fname" />
</td>
<td>
<input type="button" value="Delete" />
</td>
</tr>
<tr>
<td>
<input type="text" class="fname" />
</td>
<td>
<input type="button" value="Delete" />
</td>
</tr>
<tr>
<td>
<input type="text" class="fname" />
</td>
<td>
<input type="button" value="Delete" />
</td>
</tr>
</table>
<p>
<input type="button" value="Insert row">
</p>
On each DeleteRow(tableId,Index) function you are passing table id and static index that's why document.getElementById("mytable").deleteRow(Index) first find table node then find no of tr element as children and assigns the index to tr element start from 0 and delete the matching index tr element.
Whenever you delete first row then it will matches the 0 index from 3 elements and deletes the first row. Now there are 2 tr left with index 0 and 1 dynamically assign by table but you trying to match with 1 and 2.
for deleting second row it will delete tr with index 1 (third tr) not the second tr.
for deleting third row actual index is 0 (after deleting 2 rows) and you are passing 1 because of this reason it wont find the matching index.
Here is Simple javascript soltution.
<script>
function delRow(currElement) {
var parentRowIndex = currElement.parentNode.parentNode.rowIndex;
document.getElementById("myTable").deleteRow(parentRowIndex);
}
</script>
and html,
<table id="myTable" style="border: 1px solid black">
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="delRow(this)"></td>
</tr>
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="delRow(this)"></td>
</tr>
<tr>
<td><input type="text" id="fname"></td>
<td><input type="button" value="Delete" onclick="delRow(this)"></td>
</tr>
</table>
here is jsfiddle exmple
Click Here
Say you have the following table:
<table id="myTable">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="firstName" /></td>
<td><input type="text" name="lastName" /></td>
<td> <input type="text" name="email" /></td>
</tr>
</tbody>
<p>
<label>Insert</label>
<input type="number" value="1" id="numberOfRowsToInsert">
<input type="button" value="Insert row" id="insert-line-button">
</p>
</table>
The following jquery code will generate x number of rows entered by the user and append them to the bottom of the table with the ability to delete them if needed:
$('#insert-line-button').on("click", function(){
var noOfRows = $('#numberOfRowsToInsert').val();
for(var i = 0; i < noOfRows; i++){
$('#myTable').append("<tr>" +
"<td><input type='text' name='firstName' /></td>" +
"<td><input type='text' name='lastName' /></td>" +
"<td> <input type='text' name='email' /></td>" +
"<td><input type='button' value='Delete' id='deleteRowButton' /></td>" +
"</tr>")
}
});
And the following jquery code will remove the rows when clicked on the 'Delete' button:
$("#myTable").on('click', 'input[id="deleteRowButton"]', function(event) {
$(this).parent().parent().remove();
});
Go through below code:
You can see that this is the most basic way to create dynamic table. You can use this approach and can try yourself to remove rows from the existing table. I have not used any pluggin/ jquery. You can just copy this code and save as an html file to see how this code is working. Go head! Good luck.
<html>
<script>
function CreateTableAndRows(){
var mybody = document.getElementsByTagName("body")[0];
var newTable = document.createElement("table");
var newTableHead = document.createElement("thead");
var headRow = document.createElement("tr");
var headHead1 = document.createElement("th");
var headRowCellValue = document.createTextNode("Device Name");
headHead1.appendChild(headRowCellValue);
var headHead2 = document.createElement("th");
headRowCellValue = document.createTextNode("Start Timing");
headHead2.appendChild(headRowCellValue);
var headHead3 = document.createElement("th");
headRowCellValue = document.createTextNode("End Timing");
headHead3.appendChild(headRowCellValue);
var headHead4 = document.createElement("th");
headRowCellValue = document.createTextNode("Duration");
headHead4.appendChild(headRowCellValue);
headRow.appendChild(headHead1);
headRow.appendChild(headHead2);
headRow.appendChild(headHead3);
headRow.appendChild(headHead4);
newTableHead.appendChild(headRow);
newTable.appendChild(newTableHead);
var newTableBody = document.createElement("tbody");
for(var rowCount=0;rowCount<5;rowCount++)
{
var newTableRow = document.createElement("tr");
for(var cellCount=0; cellCount<4; cellCount++)
{
var newTableRowCell = document.createElement("td");
var cellValue = document.createTextNode("cell is row"+rowCount+", coumn "+cellCount);
newTableRowCell.appendChild(cellValue);
newTableRow.appendChild(newTableRowCell);
}
newTableBody.appendChild(newTableRow);
}
newTable.appendChild(newTableBody);
newTable.setAttribute("border","2");
mybody.appendChild(newTable);
}
</script>
</head>
<body>
<input type="submit" onclick="CreateTableAndRows();">
</body>
</html>

how to assign names to new table columns cells dynamically

At the moment ,this code can create new columns dynamically.I would like to be able to give a unique name to all cells belonging to the mother column.NB:the mother column is the tallest of them all with three columns always.Any thing with less columns is a child.
SO all the cells and the contents in the first group must have a unique name identifer like say name="Bx_1name" to identify them from the next mother's contents(BX_2name);
<table id="datble" class="form" border="1">
<tbody>
<tr>
<td>Add 1</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" />
</td>
</tr>
<tr>
<td>Add 2</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" />
</td>
</tr>
<tr>
<td>Add 3</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" />
</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
function addColumn(element) {
var tr = $(element).closest("tr")[0];
var allTrs = $(tr).closest("table").find("tr");
var found = false;
allTrs.each(function(index, item) {
if (item == tr) {
found = true;
}
var td = document.createElement("td");
if (found) {
td.innerHTML = '<label>Name</label>';
td.innerHTML += '<input type="text" required="required" name="BX_NAME[]" />';
}
item.appendChild(td);
});
}
</script>
Javascript is wellcome too.the functionality must not be changed.it must be just like this;
jsfiddle
Try this if it fits what you need.
JSFIDDLE
var counter =0;
function addColumn(element) {
var tr = $(element).closest("tr")[0];
var allTrs = $(tr).closest("table").find("tr");
var found = false;
allTrs.each(function(index, item) {
if (item == tr) {
found = true;
}
var td = document.createElement("td");
if (found) {
td.innerHTML = '<label>Name</label>';
td.innerHTML += '<input type="text" required="required" name="BX_NAME['+counter+']" value="BX_NAME['+counter+']"/>';
counter++;
}
item.appendChild(td);
});
}
i used a global counter to increment each time a cell is made.
this is just a hint you can implement this as you want to achieve. First assign same class name for all your input fields
<table id="datble" class="form" border="1">
<tbody>
<tr>
<td>Add 1</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" class="text" />
</td>
</tr>
<tr>
<td>Add 2</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" class="text" />
</td>
</tr>
<tr>
<td>Add 3</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" class="text"/>
</td>
</tr>
</tbody>
</table>
then assign diffrent id's using jquery like following
<script type="text/javascript">
$(document).ready(function (event) {
var IDCount = 1;
$('.text').each(function () {
$(this).attr('id', IDCount);
IDCount++;
});
</script>
Hope this will help

Count number of columns in a table row

I have a table similar to:
<table id="table1">
<tr>
<td><input type="text" value="" /></td>
<td><input type="text" value="" /></td>
<td><input type="text" value="" /></td>
<td><input type="text" value="" /></td>
</tr>
<tr>
<td><input type="text" value="" /></td>
<td><input type="text" value="" /></td>
<td><input type="text" value="" /></td>
<td><input type="text" value="" /></td>
</tr>
<table>
I want to count the number of td element in a row. I am trying:
document.getElementById('').cells.length;
document.getElementById('').length;
document.getElementById('').getElementsByTagName('td').length;
It did not show actual result.
document.getElementById('table1').rows[0].cells.length
cells is not a property of a table, rows are. Cells is a property of a row though
You could do
alert(document.getElementById('table1').rows[0].cells.length)
fiddle here http://jsfiddle.net/TEZ73/
Why not use reduce so that we can take colspan into account? :)
function getColumns(table) {
var cellsArray = [];
var cells = table.rows[0].cells;
// Cast the cells to an array
// (there are *cooler* ways of doing this, but this is the fastest by far)
// Taken from https://stackoverflow.com/a/15144269/6424295
for(var i=-1, l=cells.length; ++i!==l; cellsArray[i]=cells[i]);
return cellsArray.reduce(
(cols, cell) =>
// Check if the cell is visible and add it / ignore it
(cell.offsetParent !== null) ? cols += cell.colSpan : cols,
0
);
}
Count all td in table1:
console.log(
table1.querySelectorAll("td").length
)
<table id="table1">
<tr>
<td><input type="text" value="" /></td>
<td><input type="text" value="" /></td>
<td><input type="text" value="" /></td>
<td><input type="text" value="" /></td>
</tr>
<tr>
<td><input type="text" value="" /></td>
<td><input type="text" value="" /></td>
<td><input type="text" value="" /></td>
<td><input type="text" value="" /></td>
</tr>
<table>
Count all td into each tr of table1.
table1.querySelectorAll("tr").forEach(function(e){
console.log( e.querySelectorAll("td").length )
})
<table id="table1">
<tr>
<td><input type="text" value="" /></td>
<td><input type="text" value="" /></td>
<td><input type="text" value="" /></td>
<td><input type="text" value="" /></td>
</tr>
<tr>
<td><input type="text" value="" /></td>
<td><input type="text" value="" /></td>
<td><input type="text" value="" /></td>
<td><input type="text" value="" /></td>
</tr>
<table>
It's a bad idea to count the td elements to get the number of columns in your table, because td elements can span multiple columns with colspan.
Here's a simple solution using jquery:
var length = 0;
$("tr:first").find("td,th").each(function(){
var colspan = $(this).attr("colspan");
if(typeof colspan !== "undefined" && colspan > 0){
length += parseInt(colspan);
}else{
length += 1;
}
});
$("div").html("number of columns: "+length);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>single</td>
<td colspan="2">double</td>
<td>single</td>
<td>single</td>
</tr>
</table>
<div></div>
For a plain Javascript solution, see Emilio's answer.
First off, when you call getElementById, you need to provide an id. o_O
The only item in your dom with an id is the table element. If you can, you could add ids (make sure they are unique) to your tr elements.
Alternatively, you can use getElementsByTagName('tr') to get a list of tr elements in your document, and then get the number of tds.
here is a fiddle that console logs the results...
If the colspan or rowspan is all set to 1, counting the children tds will give the correct answer. However, if there are spans, we cannot count the number of columns exactly, even by the maximum number of tds of the rows. Consider the following example:
var mytable = document.getElementById('table')
for (var i=0; i < mytable.rows.length; ++i) {
document.write(mytable.rows[i].cells.length + "<br>");
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
padding: 3px;
}
<table id="table">
<thead>
<tr>
<th colspan="2">Header</th>
<th rowspan="2">Hi</th>
</tr>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
</thead>
<tbody>
<tr>
<td colspan="2">hello</td>
<td>world</td>
</tr>
<tr>
<td>hello</td>
<td colspan="2">again</td>
</tr>
</tbody>
</table>
Here is a terse script taking into account colspan.
numCols will be 0 if the table has no rows, or no columns, and it will be equal to the number of columns regardless of whether some of the cells span multiple rows or columns, as long as the table markup is valid and there are no rows shorter or longer than the number of columns in the table.
const table = document.querySelector('table')
const numCols = table.rows[0]
? [...table.rows[0].cells]
.reduce((numCols, cell) => numCols + cell.colSpan , 0)
: 0
<table id="table1">
<tr>
<td colspan=4><input type="text" value="" /></td>
</tr>
<tr>
<td><input type="text" value="" /></td>
<td><input type="text" value="" /></td>
<td><input type="text" value="" /></td>
<td><input type="text" value="" /></td>
</tr>
<table>
<script>
var row=document.getElementById('table1').rows.length;
for(i=0;i<row;i++){
console.log('Row '+parseFloat(i+1)+' : '+document.getElementById('table1').rows[i].cells.length +' column');
}
</script>
Result:
Row 1 : 1 column
Row 2 : 4 column
$('#table1').find(input).length

Categories

Resources