Storing count of table rows in a JS variable - javascript

I have some old code I am trying to poke through. This table is loaded via a Controller action returning a model, based off of a button click somewhere else in the page.
How can I find the number of rows in the table in a JS variable? I am terrible with JS. I have tried a few things and nothing has worked. Below is my code and also what I have tried to do to store the num of rows.
Table:
<hr />
<div class="row" id="ReceiptsMainDiv">
<div class="col-md-12" style="overflow-y:scroll">
<table class="table table-striped table-hover table-bordered" id="terminalReceipts">
<thead>
<tr>
<th>Terminal ID</th>
<th>Local Transaction Time</th>
<th>Amount</th>
<th>Receipt</th>
<td class="hidden"></td>
</tr>
</thead>
<tbody>
#foreach (var item in Model.TransactionsTests)
{
<tr id="#String.Concat("rowIndex", Model.TransactionsTests.IndexOf(item))">
<td>#item.TerminalID</td>
<td>#item.TransactionTime</td>
<td>#item.Amount</td>
#*<td>#Html.ActionLink("View Receipt", "ViewReceipt", new { id = item.Id }, new { #class = "btn btn-primary btn-sm" }) <br /></td>*#
<td class="transactionID hidden">#item.Id</td>
<td>
#if (item.ReceiptData == null)
{
<button class="btn btn-sm btn-primary viewReceipt" disabled>View Receipt</button>
}
else
{
<button class="btn btn-sm btn-primary viewReceipt" data-rowindex="#String.Concat("rowIndex", Model.TransactionsTests.IndexOf(item))">View Receipt</button>
}
</td>
</tr>
}
</tbody>
</table>
</div>
Here is what I have tried to do in JS:
var rowId = "#" + $(this).data("rowindex");
var row = $(rowId);
console.log(rowId);
console.log(row);
Results from the console.log don't appear to be accurate. Anything helps. Thanks

Probably you want the number of rows of your table.
// javascript
var rowsInTable = document.getElementById("terminalReceipts").getElementsByTagName("tr").length;
//jquery
var rowsInTable2 = $("#customers").children('tbody').children('tr').length;
//if you need to do something with the rows:
var rows = $("#customers").children('tbody').children('tr');
rows.each(function( index ) {
console.log( index + ": " + $( this ).text() );
});

you can also do that using jquery like this
var totalRowCount = $("#terminalReceipts tr").length; //this will give +1 row
var rowCount = $("#terminalReceipts td").closest("tr").length; //this will give actual row

Related

Hiding and un-hiding table div based off of data being returned

I have a table that I want to be hidden there is no data to be displayed.
I have a controller action that returns data to display for the table. If data is returned, I want the table to be show, otherwise I want it hidden. I have tried several approaches to this and it seems like my fix is working (for a few seconds) but then once the controller returns the model, the table becomes hidden again. I am doing something wrong. How can I fix this? Below is my code:
HTML:
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "submitForm"}))
{
<div class="row">
<div>
#Html.DropDownList("CasinoID", Model.TerminalReceiptPostData.CasinoIdDDL, "Select Casino", new { id = "cIdSearch", #class = "custom-class-for-dropdown card" })
</div>
<div>
<input id="datepicker" class="datepicker-base card" name="Date" placeholder="MM/DD/YYY" type="text"/>
</div>
<div>
<button type="submit" class="btn btn-sm btn-primary" id="search"> Search Transactions</button>
</div>
</div>
}
<hr />
<div class="row" id="ReceiptsMainDiv">
<div class="col-md-12" style="overflow-y:scroll">
<table class="table table-striped table-hover table-bordered" id="terminalReceipts">
<thead>
<tr>
<th>Terminal ID</th>
<th>Local Transaction Time</th>
<th>Amount</th>
<th>Receipt</th>
<td class="hidden"></td>
</tr>
</thead>
<tbody>
#foreach (var item in Model.TransactionsTests)
{
<tr id="#String.Concat("rowIndex", Model.TransactionsTests.IndexOf(item))">
<td>#item.TerminalID</td>
<td>#item.TransactionTime</td>
<td>#item.Amount</td>
#*<td>#Html.ActionLink("View Receipt", "ViewReceipt", new { id = item.Id }, new { #class = "btn btn-primary btn-sm" }) <br /></td>*#
<td class="transactionID hidden">#item.Id</td>
<td>
#if (item.ReceiptData == null)
{
<button class="btn btn-sm btn-primary viewReceipt" disabled>View Receipt</button>
}
else
{
<button class="btn btn-sm btn-primary viewReceipt" data-rowindex="#String.Concat("rowIndex", Model.TransactionsTests.IndexOf(item))">View Receipt</button>
}
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
Controller action:
[HttpPost]
public ActionResult Index(string CasinoID, DateTime Date)
{
//var id = Int32.Parse(Request.Form["CasinoID"].ToString());
var Cid = Request.Form["CasinoID"];
Cid = GetNumbers(Cid);
var id = Int32.Parse(Cid);
var model = TRBL.GetTransactionTestsData(id, Date);
model.TerminalReceiptPostData = TRBL.GetCasinosDDL();
return View(model);
}
and finally my JS function:
window.onload = function () {
$("#ReceiptsMainDiv").toggle();
var rowCount = $("#rowindex").length;
console.log(rowCount);
if (rowCount > 0) {
$("#ReceiptsMainDiv").toggle();
}
};
As you can see, the Form at the top contains the button, and the block below is the table that needs to be toggled.
Let me know if there is anything else you guys would need.
When you have results to show, <tr id="#String.Concat("rowIndex", Model.TransactionsTests.IndexOf(item))"> will not produce ids of "rowIndex" (unlike what you might be expecting). Instead, you will have "rowIndex0", "rowIndex1", etc. Therefore, after rowCount will be zero, and your will not toggle.

Store tr's ID and Class into a js array and read it in php [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a table with a bunch of kids, and in each tr I have the ID of the child and the class describing what did he eat, I need that when I click one button the id and class of every row must be stored into a js array, I've been trying storing into an array with push and stuffs like this...
var array = [];
$("#tbody tr").each(function() {
array.push(this.id);
});
but with no luck 'cause I need two values and it explodes...
here's the table structure
<table class="table -dark -striped" id="datatable">
<thead>
<tr>
<th class="col -xs-9 -lg-9 -xl-9 _text-right">Nombre del Alumno</th>
<th class="col -xs-3 -lg-3 -xl-3">Asistencia</th>
</tr>
</thead>
<tbody id='tbody'>
<tr id="1" class="lunch">
<td class="-user -detailed _text-right">Richard Mattey</td>
<td class="_text-right">
<div class="btn-group asistencia">
<a class="btn -l -dark -block lunch" href="javascript:void(0)" servicio="lunch">Lunch</a>
<a class="btn -l -dark -block vianda -success" href="javascript:void(0)" servicio="vianda">Vianda</a>
<a class="btn -l -dark -block inasistente" href="javascript:void(0)" servicio="inasistente"><i class="fa fa-ban"></i></a>
</div>
</td>
</tr>
When I click lunch or vianda, the corresponding TR gets a class with the name of the food:
$(document).on("click", ".asistencia a.btn", function () {
if ($(this).hasClass("-success")){ }
else {
var elIDdelAlumnoQuelediClick = $(this).closest('tr').attr('id');
var servicioDelBoton = $(this).attr('servicio');
$("#" + elIDdelAlumnoQuelediClick + " .asistencia a.btn").removeClass("-success");
$("#" + elIDdelAlumnoQuelediClick + " .asistencia a.btn." + servicioDelBoton).addClass("-success");
$("#" + elIDdelAlumnoQuelediClick).removeClass("inasistente");
$("#" + elIDdelAlumnoQuelediClick).attr('class' , servicioDelBoton);
}
});
What I need is to store into a JS Array the two values of each tr (id and class) and then send it by ajax when I click the save button, and after that get it in PHP to process it...
You can use jQuery each method to execute a function for each tr element, and get the id and class values:
var arr = [];
$('#tbody tr').each( function (i, tr) {
arr.push({
id: $(tr).attr('id'),
class: $(tr).attr('class')
});
});
OR you can use jQuery map function to iterate over all tr elements and construct your array:
var arr2 = $.map( $('#tbody tr'), function (tr) {
return {
id: $(tr).attr('id'),
class: $(tr).attr('class')
}
});
Here is a working example:
$( document ).ready(function() {
// using each function
var arr = [];
$('#tbody tr').each( function (i, tr) {
arr.push({
id: $(tr).attr('id'),
class: $(tr).attr('class')
});
});
console.log(arr);
// using jquery map function
var arr2 = $.map( $('#tbody tr'), function (tr) {
return {
id: $(tr).attr('id'),
class: $(tr).attr('class')
}
});
console.log(arr2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table -dark -striped" id="datatable">
<thead>
<tr>
<th class="col -xs-9 -lg-9 -xl-9 _text-right">Nombre del Alumno</th>
<th class="col -xs-3 -lg-3 -xl-3">Asistencia</th>
</tr>
</thead>
<tbody id='tbody'>
<tr id="1" class="lunch">
<td class="-user -detailed _text-right">Richard Mattey</td>
<td class="_text-right">
<div class="btn-group asistencia">
<a class="btn -l -dark -block lunch" href="javascript:void(0)" servicio="lunch">Lunch</a>
<a class="btn -l -dark -block vianda -success" href="javascript:void(0)" servicio="vianda">Vianda</a>
<a class="btn -l -dark -block inasistente" href="javascript:void(0)" servicio="inasistente"><i class="fa fa-ban"></i></a>
</div>
</td>
</tr>
</tbody>
</table>
You can iterate over all the tr's that are in tbody with querySelectorAll.
Then just collect the id & class name from the DomNode, something like that:
const trs = Array.from(document.querySelectorAll('tbody > tr'));
const data = trs.map((tr) => ({
id: tr.id,
class: tr.classList.toString()
}));
console.log(data);
<table class="table -dark -striped" id="datatable">
<thead>
<tr>
<th class="col -xs-9 -lg-9 -xl-9 _text-right">Nombre del Alumno</th>
<th class="col -xs-3 -lg-3 -xl-3">Asistencia</th>
</tr>
</thead>
<tbody id='tbody'>
<tr id="1" class="lunch">
<td class="-user -detailed _text-right">Richard Mattey</td>
<td class="_text-right">
<div class="btn-group asistencia">
<a class="btn -l -dark -block lunch" href="javascript:void(0)" servicio="lunch">Lunch</a>
<a class="btn -l -dark -block vianda -success" href="javascript:void(0)" servicio="vianda">Vianda</a>
<a class="btn -l -dark -block inasistente" href="javascript:void(0)" servicio="inasistente"><i class="fa fa-ban"></i></a>
</div>
</td>
</tr>
</tbody>
</table>
You can fetch the ids and classes of each tr entry in your table by using the following function:
/* The function that fetches the data. */
function fetchData() {
var
/* Create an object to store the data. */
data = {},
/* Get every 'tr' element of the 'tbody'. */
elements = document.querySelectorAll("#tbody > tr");
/* For each element, save the id as a property & the class as a value in the obj. */
[].forEach.call(elements, (element) => data[element.id] = element.className);
/* Stringify and return the data to pass them over to the server. */
return JSON.stringify(data);
}
The above function stores the data as property-value pairs in an object and also stringifies the object, so that you can pass that to the server. Then you can easily the access in PHP with a foreach as construct:
Example:
foreach ($data as $id => $class) {
# ...
}
Snippet:
/* The function that fetches the data. */
function fetchData() {
var
/* Create an object to store the data. */
data = {},
/* Get every 'tr' element of the 'tbody'. */
elements = document.querySelectorAll("#tbody > tr");
/* For each element, save the id as a property & the class as a value in the obj. */
[].forEach.call(elements, (element) => data[element.id] = element.className);
/* Stringify and return the data to pass them over to the server. */
return JSON.stringify(data);
}
<table class="table -dark -striped" id="datatable">
<thead></thead>
<tbody id='tbody'>
<tr id="1" class="lunch"></tr>
<tr id="2" class="breakfast"></tr>
<tr id="3" class="brunch"></tr>
<tr id="4" class="dinner"></tr>
<tr id="5" class="supper"></tr>
</tbody>
</table>
<button onclick = "console.log(fetchData())">Fetch Table Data</button>

calcul jQuery does not work

I try to change value by default with a calcul : value by default * quantity / 100. In my script something does not work because nothing happened, I can't find what! (jQuery is very new for me...)
$(function () {
$("#calcul").click(function (e) {
e.preventDefault();
var valeur = parseFloat($("#valquantite").text() );
$("#nutrition > tbody > tr").each(function () {
var valeurOrigin = parseFloat($(this).find("td").eq(1).text().replace(",", "."));
var newValeur;
if ($.isNumeric(valeurOrigin) === true) {
newValeur = valeurOrigin*valeur/100;
newValeur = Math.ceil(newValeur*1000)/1000;
} else {
newValeur = $(this).find("td").eq(1).text();
}
$(this).find("td").eq(2).html(newValeur);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="overflow-x:scroll;;" name="formu">
<table class="table table-striped" id="nutrition" >
<thead>
<tr>
<th>Aliments</th>
<th id="qty">Poids</th>
<th class="generaux">Energie kJ</th>
<th class="generaux">Energie kcal</th>
</thead>
<tbody class="text-primary" id="">
<tr><td>Pain au lait, préemballé:</td><td id="valquantite"><strong>35gr</strong></td>
<td class="generaux" name="">1510</td>
<td class="generaux">358</td>
</tr>
<tr><td>Total</td>
<td><strong>50gr</strong></td>
</tr>
</tbody>
</table>
<input class="btn btn-primary" type="button" value="Calculer" id="calcul" />
What i try to do is that the first column after the name retrieves the quantities from a table (different for each row), then I retrieve the values ​​by default columns energie_kj, energie_kcal, proteines, etc .. from a table (there are 60 Columns !! they are already calculated by default, I do not need to do any conversion). Some cells contain text (example: nc, traces, <) that I want to display as text. Then I have to calculate the total of each column (ignoring cells that contain text). That's my problem! I posted another question for the same problem with a code in js that works almost but not completely ... here: Javascript problems with NaN
Thanks in advance for your answers.
Hope this will help you. Replace your code with following : I've just parse your valeur variable and replaced > sign when calling .each function and applied Id=nutrition to table rather than tbody tag.
$(function () {
$("#calcul").click(function (e) {
e.preventDefault();
var valeur = parseInt($("#valquantite").text());
$("#nutrition tbody tr").each(function () {
var valeurOrigin = parseFloat($(this).find("td").eq(2).text().replace(",", "."));
var newValeur;
if ($.isNumeric(valeurOrigin) === true) {
newValeur = valeurOrigin*valeur/100;
newValeur = Math.ceil(newValeur*1000)/1000;
} else {
newValeur = $(this).find("td").eq(1).text();
}
$(this).find("td").eq(2).html(newValeur);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="overflow-x:scroll;;" name="formu">
<table class="table table-striped" id="nutrition">
<thead>
<tr>
<th>Aliments</th>
<th id="qty">Poids</th>
<th class="generaux">Energie kJ</th>
<th class="generaux">Energie kcal</th>
</thead>
<tbody class="text-primary">
<tr><td>Pain au lait, préemballé:</td><td id="valquantite"><strong>35gr</strong></td>
<td class="generaux" name="">1510</td>
<td class="generaux">358</td>
</tr>
<tr><td>Total</td>
<td><strong>50gr</strong></td>
</tr>
</tbody>
</table>
<input class="btn btn-primary" type="button" value="Calculer" id="calcul" />
The issue may be, we don't know exactly what it is you're trying to calculate or where the data comes from. The valQuantite to which you refer, does that change for each row? If so, why is it defined outside of the each function? If not, why does it refer to a value from the first row of the table?
Doing a little research, you seem to want to take the quantity column and use that along with the energie kJ column to calculate... something. I'd suggest using classes for the three columns, valquantite, energie-kj, and energie-kcal, which you can then use to manipulate the individual columns in a meaningful way. Using $(this).find("td").eq(2).text() is only as good as the coder -- what if the column layout changes? Instead, simply use $(this).find(".energie-kj").text() and you're good.
Now, having gotten to displaying the kj as you'd like (by taking the qty and multiplying it by the kj, then rounding), you can calculate the kCal by dividing that number by 4.1868 and rounding as you'd like.
But note, I've modified your code -- the quantity seems to change with each row, so I've moved valQuantite inside the each statement. Also, I can't stress enough, I've commented my code to the point of silliness. Doing so makes it far easier to track what each line of code is SUPPOSED to be doing, as well as what it's actually doing. And use your console, it is your debugging FRIEND! lol
$(function() {
// When the button is clicked, calculate the values.
$("#calcul").click(function(e) {
// First, make sure the button doesn't submit...
e.preventDefault();
// Each row is handled individually, so
$("#nutrition > tbody > tr").each(function() {
// First, get the qty for this row
var valeur = parseFloat($(this).find(".valquantite").text());
/****
* Here is a case. We have hard-wired to use the
* third column of the table for the original val,
* but we could also add a class for this col and
* reference that: $(this).find(".energie-kj");
****/
var valeurOrigin = parseFloat($(this).find("td").eq(2).text().replace(",", "."));
var energyKJ, energyKCal;
// If the energie kJ value is numeric, we do the first
if ($.isNumeric(valeurOrigin) === true) {
// calculate some value from the energie kJ and qty,
energyKJ = valeurOrigin * valeur / 100;
// 1 kCal = 4.1868 kJ, so do the conversion
energyKCal = (energyKJ/4.1868).toFixed(2);
energyKJ = energyKJ.toFixed(2);
} else {
// If the energie kJ value is NOT numeric, we simply
// set the displayed value to this
newValeur = $(this).find("td").eq(2).text();
}
$(this).find(".energie-kj").text(energyKJ);
$(this).find(".energie-kcal").text(energyKCal);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="overflow-x:scroll;;" name="formu">
<table class="table table-striped" id="nutrition">
<thead>
<tr>
<th>Aliments</th>
<th id="qty">Poids</th>
<th class="generaux">Energie kJ</th>
<th class="generaux">Energie kcal</th>
</thead>
<tbody class="text-primary" id="">
<tr>
<td>Pain au lait, préemballé:</td>
<td class="valquantite"><strong>35gr</strong></td>
<td class="generaux energie-kj" name="">1510</td>
<td class="generaux energie-kcal">358</td>
</tr>
<tr>
<td>Some other thing...:</td>
<td class="valquantite"><strong>45gr</strong></td>
<td class="generaux energie-kj" name="">1510</td>
<td class="generaux energie-kcal">358</td>
</tr> <tr>
<td>Total</td>
<td><strong>50gr</strong></td>
</tr>
</tbody>
</table>
<input class="btn btn-primary" type="button" value="Calculer" id="calcul" />

Hide/show row in a dynamic table using jscript

I have a json data through ajax call and displayed it in a dynamic html table based on the length of data object obtained from ajax using jscript. Now i need to hide or show data in the table on the basis of a drop down option selected, for example if the user clicks on an item "less than 100" from the drop down, only the related rows which has values less than 100 should be displayed and other rows should be hidden.
$.ajax({
url: "http://finance.google.com/finance/info?client=ig&q=" +CompName+ "",
type: "get",
dataType: "jsonp",
success:function(data, textstatus, jqXHR){
drawTable(data);
}
});
function drawTable(data) {
for (var i = 0; i < data.length; i++) {
drawRow(data[i]);
}
}
function drawRow(rowData){
var row= $("<tr />")
$("#table").append(row);
row.append($("<td>" + rowData.t + "</td>"));
row.append($("<td>" + rowData.l_cur + "</td>"));
row.append($("<td>" + rowData.c + "</td>"));
row.append($("<td>" + rowData.lt + "</td>"));
}
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Select the value
<span class="caret"></span></button>
<ul class="dropdown-menu">
<li>Below 100</li>
<li>100-300</li>
<li>300-600</li>
<li>600-1000</li>
<li>above 1000</li>
</ul>
</div>
<div class="table-responsive">
<table id="table" class="table table-striped">
<tr>
<th>Name</th>
<th>Price</th>
<th>Change</th>
<th>Date</th>
</tr>
</table>
</div>
Here's the html AND javascript snippet.
In order to make it work correctly, apart from the text for li, you should also make use of data-attributes which would give you the range to lookup.
Following is an example which shows how you can make use of it.
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Select the value
<span class="caret"></span></button>
<ul class="dropdown-menu">
<li>Below 100</li>
<li>100-300</li>
</ul>
</div>
<div class="table-responsive">
<table id="table" class="table table-striped">
<tr>
<th>Name</th>
<th>Price</th>
<th>Change</th>
<th>Date</th>
</tr>
<tr>
<td>ABC</td>
<td>99</td>
<td>+10</td>
<td>12/12/2014</td>
</tr>
<tr>
<td>EFG</td>
<td>79</td>
<td>+10</td>
<td>12/12/2014</td>
</tr>
<tr>
<td>HIJ</td>
<td>104</td>
<td>+20</td>
<td>12/12/2014</td>
</tr>
</table>
</div>
<script>
$('li').on("click",function()
{
var minRange = $(this).find('a').data("min"); // get the data-min attribute to get the min range
var maxRange = $(this).find('a').data("max"); // get the data-min attribute to get the max range
$("#table tr").each(function() // iterate through each tr inside the table
{
var data = $(this).find('td').eq(1).text(); // get the price td column value from each tr
if(!isNaN(data) && data != "") // skip th tags inside tr and any other td missing the price column value
{
$(this).hide(); // hide all tr by default
if(data >= minRange && data <= maxRange) // check if the price td column value falls within the range
$(this).show(); // show the current tr
}
});
});
</script>
Example : http://jsfiddle.net/RxguB/205/
We listen for changes on the select event. We then get the criteria we are using to filter records by getting the value of the selected item. We create multiple filters based on the value. We're going to toggle between showing and hiding them.
$("select").on("change", function() {
var criteria = ($(":selected").prop("value"));
var filterOne = $("td:nth-child(2)").filter(function() {
return Number($(this).html()) >= 100;
});
var filterTwo = $("td:nth-child(2)").filter(function() {
return Number($(this).html()) < 100;
});
if (criteria == "Less than 100") {
filterOne.parent().hide();
filterTwo.parent().show();
}
else {
filterTwo.parent().hide();
filterOne.parent().show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option>Less than 100</option>
<option>More than 100</option>
</select>
<table>
<tr>
<th>Name</th>
<th>Price</th>
<th>Change</th>
<th>Date</th>
</tr>
<tr>
<td>Stock 1</td>
<td>72</td>
<td>+5</td>
<td>3/4/2012</td>
</tr>
<tr>
<td>Stock 2</td>
<td>102</td>
<td>+8</td>
<td>5/7/2013</td>
</tr>
<tr>
<td>Stock 3</td>
<td>90</td>
<td>-3</td>
<td>3/16/2013
</tr>
</table>

Counting rows on a particular table

I have a page that the user can dynamically add rows or tables to. I need to count the rows on a given table using jQuery to see if I just need to insert a row or a row and the header. Right now the count is just counting all rows on all tables. I am using jQuery 1.7.2 and the jquery templeter.
<div id="ClonePoint">
<button id="exitSection" class="closesection"><span>Close</span></button> <br /> <br />
<button class="btnEncode" id="buttonEncode">Encode</button>
<input id="encryptedTokenClone" />
<button class="btnDecode" id="buttonDecode">Decode</button>
<table class="tokenTable" cellpadding="3px">
<tbody class="tokenBody" >
</tbody>
</table>
<button id="addRow" class="addingRow">Add Row</button>
</div>
And the jQuery that is adding the rows
$('#BackgroundArea').on('click', '.addingRow', function () {
var selectedDiv = $(this).parent();
var selectedTable = $(selectedDiv).children('.tokenTable');
var rowCount = 0;
rowCount = $('.tokenTable .tokenBody').children('tr').length;
if (rowCount > 0) {
$("#tokenAddRowTemplate")
.tmpl()
.appendTo(selectedTable);
} else {
$("#TableHeader")
.tmpl()
.appendTo(selectedTable);
$("#tokenAddRowTemplate")
.tmpl()
.appendTo(selectedTable);
}
});
The html for the insert is
<script id="TableHeader" type="text/html">
<tr id="TableHead">
<th width="55px">Delete Row</th>
<th align="right"> Key </th>
<th align="left"> Value </th>
</tr>
</script>
<script id="tokenAddRowTemplate" type="text/html">
<tr id="tokenRow">
<td class="deleteRow" id="tokenCell">
<button class="deleteRow">
<span>delete row</span>
</button>
</td>
<td class="keyValue" id="tokenCell">
<div class="edit" contenteditable="true"></div>
</td>
<td class="valueValue" id="tokenCell">
<div class="edit" contenteditable="true"></div>
</td>
</tr>
</script>
This should give tr count in your table.
$("#yourTableId tr").length
Is this what your are looking for ?
If each table is followed by its own "Add Row" button:
var $table = $(this).prev(),
rowCount = $table.find('.tokenBody').children('tr').length;
if (rowCount > 0) {
...
This assumes the "Add Row" button immediately follows the table.
To make the code less brittle, you could consider using a container element, like this:
<div class="tokenTableContainer">
<table class="tokenTable">
...
<table>
<button class="addingRow">...</button>
</div>
Then you can do this:
$('.addingRow').click(function() {
var $table = $(this).closest('.tokenTableContainer').find('.tokenTable');
...
});

Categories

Resources