How to navigate textboxes in between different tables using arrow keys? - javascript

I have the following code, it is working that is navigating between the textboxes, but the issue is it is navigating only within one table, but am having different tables in my page. How to make it work?
$('input[type="text"],textarea').keyup(function(e){
if(e.which==39 || e.which==13)
$(this).closest('td').next().find('input[type="text"],textarea').focus();
else if(e.which==37 || e.which==8)
$(this).closest('td').prev().find('input[type="text"],textarea').focus();
else if(e.which==40 || e.which==13)
$(this).closest('tr').next().find('td:eq('+$(this).closest('td').index()+')').find('input[type="text"],textarea').focus();
else if(e.which==38 || e.which==8)
$(this).closest('tr').prev().find('td:eq('+$(this).closest('td').index()+')').find('input[type="text"],textarea').focus();
});
<form>
<table width="960" align="center" cellspacing="20" cellpadding="15" id="navigate">
<thead>
<th align="center"></th>
<th align="center"></th>
<th align="center"></th>
<th align="center"></th>
</thead>
<tbody>
<tr>
<td colspan="4" style="font-size:15px;"><b>ADVERTISING:</b></th>
</tr>
<tr>
<th></th>
<th align="center">DOMESTIC($)</th>
<th align="center">INTERNATIONAL($)</th>
<th align="center">NOTES</th>
</tr>
<tr>
<td class="spending_table_title" title="<?php echo $this->data[14]->content; ?>"><span style="text-transform: uppercase;"><?php echo $this->data[13]->content; ?></span></td>
<td ><input type="text" value="" name="actual_marketing_dom_print" id="actual_marketing_dom_print" size="30" style="height:20px; width:155px;" onChange="total_dom_advt();total_marketing_spending();format(this);"/> </td>
<td ><input type="text" value="" name="actual_marketing_intl_print" id="actual_marketing_intl_print" size="30" style="height:20px; width:155px; " onChange="total_intl_advt();total_marketing_spending();format(this);"/></td>
<td ><textarea name="actual_marketing_print_notes" id="actual_marketing_print_notes" style="height:32px; width:300px;" rows="3" cols="20" class ="notes"> </textarea></td>
</tr>
</tbody>
</table>
</div>
<br>
<br>
<div class="divgrid">
<table width="960" align="center" cellspacing="20" cellpadding="15" id="navigate">
<thead>
<th style="width:60%;"></th>
<th></th>
<th></th>
</thead>
<tbody>
<tr>
<td colspan="3" style="font-size:15px;font-weight:bold;">TOTAL PRESS AND PUBLIC RELATIONS (DOMESTIC AND INTERNATIONAL COMBINED):</td>
</tr>
<tr>
<th></th>
<th align="center">$</th>
<th align="center">NOTES</th>
</tr>
<tr>
<td class="spending_table_title" title="<?php echo $this->data[31]->content; ?>"><span style="text-transform: uppercase;"><?php echo $this->data[30]->content; ?></span></td>
<td ><input type="text" value="" name="actual_marketing_industry_relations" id="actual_marketing_industry_relations" size="30" style="height:20px; width:155px; " onChange="total_press_public();total_marketing_spending();format(this);"/></td>
<td ><textarea name="actual_marketing_industry_relations_notes" id="actual_marketing_industry_relations_notes" style="height:32px; width:300px;" rows="3" cols="20" class ="notes"> </textarea></td>
</tr>
</tbody>
</table>
</form>
in my code am having two tables, after completing the textboxes in one table am not table to navigate to next table textboxes, i was not known how to do this

Interesting question, and hopefully you will find this helpful.
What I'm doing here is to check if there is an input above or below to go to with if (t.length == 0), and if not, move to the corresponding cell in the next or previous table instead.
$(document).ready(function () {
$('input[type="text"],textarea').keyup(function (e) {
if (e.which == 39) {
$(this).closest('td').next().find('input[type="text"],textarea').focus();
} else if (e.which == 37) {
$(this).closest('td').prev().find('input[type="text"],textarea').focus();
} else if (e.which == 40) {
var t = $(this).closest('tr').next().find('td:eq(' + $(this).closest('td').index() + ')').find('input[type="text"],textarea');
if (t.length == 0) {
t = $(document).find('table:eq(' + ($('table').index($(this).closest('table')) + 1) + ')').find('tbody tr td').parent().first().find('td:eq(' + $(this).closest('td').index() + ')').find('input[type="text"]:not([readonly]),textarea');
}
t.focus();
} else if (e.which == 38) {
var t = $(this).closest('tr').prev().find('td:eq(' + $(this).closest('td').index() + ')').find('input[type="text"],textarea');
if (t.length == 0) {
t = $(document).find('table:eq(' + ($('table').index($(this).closest('table')) - 1) + ')').find('tbody tr td').parent().last().find('td:eq(' + $(this).closest('td').index() + ')').find('input[type="text"]:not([readonly]),textarea');
}
t.focus();
}
});
});
http://jsfiddle.net/zxTfb/5/
Please note that right now, this only works on multiple tables on top of each other, not side by side. If you need them side by side, you could copy what I did for keys 40 and 38 and modify it to work for 39 and 37 as well.
Hope it helps.
Further explanation
Let's break down this line of code and look at inner workings:
t = $(document).find('table:eq(' + ($('table').index($(this).closest('table')) - 1) + ')').find('tbody tr td').parent().last().find('td:eq(' + $(this).closest('td').index() + ')').find('input[type="text"]:not([readonly]),textarea');
First we find the table above the one we are currently in. This is done with the selector :eq() which selects an element, table in this case, by it's index. We select the table with our current tables index -1 to get the table above.
$(document).find('table:eq(' + ($('table').index($(this).closest('table')) - 1) + ')')
Now that we have the table above our current position, we find the last <tr> element that does contain a <td>, by first looking for all <td>, then move up to it's parent <tr> with .parent() and finally select the last one (bottom row) with .last().
.find('tbody tr td').parent().last()
Now we know which <tr> to look in, so we move ahead and look for the specific <td> by index, so that we end up in the right column, corresponding to the one we are currently in. This is similar to when we found the <table> by index at the top.
.find('td:eq(' + $(this).closest('td').index() + ')')
Finally, we now have our correct <td> element and now all that remains is to find our <input> or <textarea> that isn't readonly. We do this simply by selecting them like so
.find('input[type="text"]:not([readonly]),textarea');
And now we know where to move in the table above. Since we set t to this new element, all that remains is to move the focus there with t.focus().
And there you have it!

How about this?
Use a global counter to assign IDs to your inputs. Then, since you know what ID triggered the event, you just add or subtract from that ID to get the new ID you should go to. Here's some code:
<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function() {
console.log("hej");
$('input[type="text"],textarea').keyup(function(e){
if(e.which==39 || e.which==13) {
var thisId = parseInt(this.id);
$("#" + (thisId + 1)).focus();
} else if(e.which==37 || e.which==8) {
var thisId = parseInt(this.id);
$("#" + (thisId - 1)).focus();
} else if(e.which==40 || e.which==13) {
var thisId = parseInt(this.id);
$("#" + (thisId + 4)).focus();
} else if(e.which==38 || e.which==8) {
var thisId = parseInt(this.id);
$("#" + (thisId - 4)).focus();
}
});
});
</script>
</head>
<body>
<form>
<table>
<tr>
<td><input type="text" id="1" name="5"></td>
<td><input type="text" id="2" name="6"></td>
<td><input type="text" id="3" name="7"></td>
<td><input type="text" id="4" name="8"></td>
</tr>
<tr>
<td><input type="text" id="5" name="5"></td>
<td><input type="text" id="6" name="6"></td>
<td><input type="text" id="7" name="7"></td>
<td><input type="text" id="8" name="8"></td>
</tr>
<tr>
<td><input type="text" id="9" name="5"></td>
<td><input type="text" id="10" name="6"></td>
<td><input type="text" id="11" name="7"></td>
<td><input type="text" id="12" name="8"></td>
</tr>
</table>
<table>
<tr>
<td><input type="text" id="13" name="5"></td>
<td><input type="text" id="14" name="6"></td>
<td><input type="text" id="15" name="7"></td>
<td><input type="text" id="16" name="8"></td>
</tr>
<tr>
<td><input type="text" id="17" name="5"></td>
<td><input type="text" id="18" name="6"></td>
<td><input type="text" id="19" name="7"></td>
<td><input type="text" id="20" name="8"></td>
</tr>
<tr>
<td><input type="text" id="21" name="5"></td>
<td><input type="text" id="22" name="6"></td>
<td><input type="text" id="23" name="7"></td>
<td><input type="text" id="24" name="8"></td>
</tr>
</table>
</form>
</body>
</html>

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>

Get all the values of td columns from table where checkbox is checked

I have a table as below:
..
There have been multiple questions asked for getting the values but in this case I should always have a parent item name. Suppose If a user selected only one subitem in "Shirts", then I should be able to get all the values from the selected tr and with that I need parent item name also i.e "shirts" and if some one clicks on all the subitems of a parent item, then all the values of all tr are need to be in some sort of array object on click of a "Save" button. I am trying hard to do this. Any help would be really appreciated. Though I have attached the HTML but this HTML is being generated at run time.
HTML:
<table>
<tr>
<td> </td>
<td> </td>
<td>Name</td>
<td>Sub Item</td>
<td>User Input</td>
</tr>
<tr>
<td>
<input type="checkbox" id="chkGroup1" class="cls1" onclick="checkUncheckAll(this);" />
</td>
<td>Shirts
</td>
</tr>
<tr>
<td>
<input type="checkbox" class="cls1" name="Group1" onclick="CheckCorrespondingHeader(this);" /></td>
<td> </td>
<td>Item1</td>
<td>SubItem1</td>
<td>
<input id="1datepicker" name="1datepicker" type="text" /><script>
</script></td>
</tr>
<tr>
<td>
<input type="checkbox" class="cls1" name="Group1" onclick="CheckCorrespondingHeader(this);" /></td>
<td> </td>
<td>Item2</td>
<td>SubItem2</td>
<td>
<input id="2datepicker" name="2datepicker" type="text" /><script>
</script></td>
</tr>
<tr>
<td>
<input type="checkbox" class="cls1" name="Group1" onclick="CheckCorrespondingHeader(this);" /></td>
<td> </td>
<td>Item3</td>
<td>SubItem3</td>
<td>
<input id="3datepicker" name="3datepicker" type="text" /><script>
</script></td>
</tr>
<tr>
<td>
<input type="checkbox" id="chkGroup2" class="cls2" onclick="checkUncheckAll(this);" />
</td>
<td>Jeans
</td>
</tr>
<tr>
<td>
<input type="checkbox" class="cls2" name="Group2" onclick="CheckCorrespondingHeader(this);" /></td>
<td> </td>
<td>Item4</td>
<td>SubItem4</td>
<td>
<input id="4datepicker" name="4datepicker" type="text" /><script>
</script></td>
</tr>
<tr>
<td>
<input type="checkbox" class="cls2" name="Group2" onclick="CheckCorrespondingHeader(this);" /></td>
<td> </td>
<td>Item5</td>
<td>SubItem5</td>
<td>
<input id="5datepicker" name="5datepicker" type="text" /><script>
</script></td>
</tr>
<tr>
<td>
<input type="checkbox" class="cls2" name="Group2" onclick="CheckCorrespondingHeader(this);" /></td>
<td> </td>
<td>Item6</td>
<td>SubItem6</td>
<td>
<input id="6datepicker" name="6datepicker" type="text" /><script>
</script></td>
</tr>
</table>
Script code looks like below:
<script>
function checkUncheckAll(sender) {
var chkElements = document.getElementsByClassName(sender.className);
for (var i = 0; i < chkElements.length; i++) {
chkElements[i].checked = sender.checked;
}
}
function CheckCorrespondingHeader(sender) {
ControlLength = $("[name='" + sender.name + "']").length;
var countchecks = 0;
$("[name='" + sender.name + "']").each(function () {
if ($(this).prop('checked') == true) {
countchecks = countchecks + 1;
}
});
if (ControlLength == countchecks) {
$("#chk" + sender.name).attr('checked', 'checked');
}
else {
$("#chk" + sender.name).prop('checked', false);
}
}
function PickAllCheckedRows() {
}
</script>
As far as I can tell your code should work if you fix one issue. You are determining the number of sub rows that need to be checked to make the header row be checked using $("[name='" + sender.name + "']").length;. But unless I'm mistaken sender.name is never set. Of course if you set it this still won't work because your each function will include the header row. There are several solutions to this but I would recommend using a data attribute instead of the name attribute like so:
Markup:
<table>
<tr>
<!-- head -->
<td><input type="checkbox" data-head-for-group="Group1" ... /></td>
</tr>
<tr>
<!-- row 1 -->
<td><input type="checkbox" data-in-group="Group1" ... /></td>
</tr>
<tr>
<!-- row 2 -->
<td><input type="checkbox" data-in-group="Group1" ... /></td>
</tr>
<tr>
<!-- head -->
<td><input type="checkbox" data-head-for-group="Group2" ... /></td>
</tr>
<tr>
<!-- row 3 -->
<td><input type="checkbox" data-in-group="Group2" ... /></td>
</tr>
</table>
Script:
function CheckCorrespondingHeader(sender) {
var group = $("[data-in-group='" + sender.data('headForGroup') + "']");
var groupSize = group.length;
var countchecks = 0;
group.each(function () {
if ($(this).prop('checked') === true) {
countchecks = countchecks + 1;
}
});
if (groupSize === countchecks) {
$(sender).attr('checked', 'checked');
} else {
$(sender).prop('checked', false);
}
}

Add new Id For Text Box inside tr on clone jquery

I have a table and on button click i am adding row using .clone and adding id using .prop now What i want to do is i want to find text boxes with in tr and change ids for it How can i do it
Here is My html
<table class="table purchasemanagement customtabl-bordered " id="tblpurchaseproductdes">
<thead>
<tr>
<th><input type="checkbox" onclick="select_all()" class="check_all"></th>
<th>Product Description*</th>
<th>No's*</th>
<span class="error" id="purchse_no" style="color:red"></span>
<th>Capacity*</th>
<span class="error" id="purchse_errorcapacity" style="color:red"></span>
<th>Quantity</th>
<th>Full/Empty</th>
</tr>
</thead>
<tbody id="puchasedescbody">
<tr class="purchaserow">
<td><input class="case" type="checkbox"></td>
<td>
<select class='form-control drpdwn_pdtdescription' id='drpdwn_pdtdescription' name='pdtdescription'></select>
</td>
<td><input class='form-control pdtdesc_nos' id="no_1" name='nos' /></td>
<td><input class='form-control pdtdesc_capacity' id="capacity_1" name='capacity' /></td>
<td><input class='form-control pdtdesc_qty' id="quantity_1" name='quantity' readonly /></td>
<td><input class='case1 pdtdesc_full' type='checkbox' name='full' checked='checked'></td>
</tr>
</tbody>
</table>
js
$(".purchasemore").on('click', function() {
var cloneCount = 1;
// var row = $(".purchasemanagement tr:last").clone().find(':input').val('').end();
var row = $(".purchasemanagement tr:last").clone().prop('id', 'klon' + cloneCount);
// var test = $(this).find('input[name$="nos"]').attr("id");
// alert(test);
$('.purchasemanagement').append(row);
});
For my code It is Adding id for tr
i want to change id for nos,capacity
Thanks
In your commented code you need to access those elements using :
row.find('.pdtdesc_capacity').attr('id','capacity_' + cloneCount);

show/hide div based on radio button checked

I am trying to show/hide text fields based on checked radio buttons checked. Here is my code; it works fine if I don't use table tags, when using table tags, Javascript doesn't work
<script type="text/javascript">
function onchange_handler(obj, id) {
var other_id = (id == 'personal')? 'corporate' : 'personal';
if(obj.checked) {
document.getElementById(id + '_form_fields').style.display = 'block';
document.getElementById(other_id + '_form_fields').style.display = 'none';
} else {
document.getElementById(id + '_form_fields').style.display = 'none';
document.getElementById(other_id + '_form_fields').style.display = 'block';
}
}
</script>
<table>
<tr>
<td colspan="2">
<input type="radio" name="tipo_cadastro" value="individual_form" id="individual_form" style="margin:0px !important" onchange="onchange_handler(this, 'personal');" onmouseup="onchange_handler(this, 'personal');">
<strong>Individual Form</strong>
<input type="radio" name="tipo_cadastro" value="corporation_form" id="corporation_form" style="margin:0px !important" onchange="onchange_handler(this, 'corporate');" onmouseup="onchange_handler(this, 'corporate');">
<strong>Corporation Form</strong>
</td><tr>
<!-- If Individual Form is checked -->
<div id="personal_form_fields">
<tr><td>First Name</td>
<td><input type="text" name="First_Name" value=""></td>
</tr>
<tr><td>Last Name</td>
<td><input type="text" name="Last_Name" value=""></td>
</tr>
</div>
<!-- If Corporation Form is checked -->
<div id="corporate_form_fields" style="display: none;">
<tr><td>Company</td>
<td><input type="text" name="company_name" value=""></td>
</tr>
</div>
</table>
What putvande might mean by "strange markup" is that your <div id="personal_form_fields"> is in the table, with its parent being a table tag. That's not right. The tr should contain the td, which contains the div, not the other way around.
If you're trying to change visibility, this syntax error could be the problem.
Simply add a class to the TR of each group and show / hide the class...
<script type="text/javascript">
function onchange_handler(obj, id) {
var other_id = (id == 'personal')? 'corporate' : 'personal';
if(obj.checked)
{
class_display(id + '_form_fields','block');
class_display(other_id + '_form_fields','none');
} else {
class_display(id + '_form_fields','none');
class_display(other_id + '_form_fields','block');
}
}
function class_display(tr_class,display)
{
var tr_ele = document.getElementsByClassName(tr_class);
for (var i = 0; i < tr_ele.length; ++i) {
var item = tr_ele[i];
item.style.display = display;
}
}
</script>
<table>
<tr>
<td colspan="2">
<input type="radio" name="tipo_cadastro" value="individual_form" id="individual_form" style="margin:0px !important" onChange="onchange_handler(this, 'personal');" onmouseup="onchange_handler(this, 'personal');" checked>
<strong>Individual Form</strong>
<input type="radio" name="tipo_cadastro" value="corporation_form" id="corporation_form" style="margin:0px !important" onchange="onchange_handler(this, 'corporate');" onmouseup="onchange_handler(this, 'corporate');">
<strong>Corporation Form</strong>
</td>
<tr>
<!-- If Individual Form is checked -->
<tr class="personal_form_fields">
<td>First Name</td>
<td><input type="text" name="First_Name" value=""></td>
</tr>
<tr class="personal_form_fields">
<td>Last Name</td>
<td><input type="text" name="Last_Name" value=""></td>
</tr>
<!-- If Corporation Form is checked -->
<tr class="corporate_form_fields" style="display: none;">
<td>Company</td>
<td><input type="text" name="company_name" value=""></td>
</tr>
</table>

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