Get number of rows on specific datatables page? - javascript

I'm trying to get the count of the number of rows on the current dataTables page. If I do this:
alert($('.tableViewer tbody tr').length)
It gives me the a non-accurate row count (I think it adds the current page and the last one?).
Anyway, I'm just trying to get the row count on the page I'm actually on. Does anyone know how to do this?
Here's my delete button:
function fnDelete(elem){
if (selected.length>0) {
var c;
c = confirm('Are you sure you want to delete the selected ${displayTableName}?');
if (c) {
// Create delete url from editor url...
var deleteURL = (urlstr.substring(0, urlstr.lastIndexOf('/') + 1)) + "delete.do";
alert($('.tableViewer tbody tr').length)
deleteRecord(deleteURL,selected[0]);
alert($('.tableViewer tbody tr').length)
if ( $('.tableViewer tbody tr').length === 1) {
setTimeout(function() { oTable.fnPageChange('last'); }, 100);
}
}
}
}

The tr elements may be on the page, but not visible. Try this!
$('.tableViewer tbody tr:visible').length

Related

Jquery - check column checkboxes then do something with those rows

I've been trying to find a good match to my question, but nothing really concrete. I'm still learning and don't know exactly what I'm missing.
So my code can be found here: Fiddle
This is a simplified version of what I'm working with. In the final version, I will upload a csv file to the html table you see there (id="dvCSV"). Upon uploading, the table will look like it is shown (with added dropdowns and a column of checkboxes). The checkboxes come "pre-chcecked" when I generate them but what I want is the user to be able to turn "off" the rows that I do not want to calculate on.
I'll run you through the process:
This function reads the columns that the user designates. I don't know which column they will upload the data into.
function CheckLocations() {
//Checks the uploaded data for the locations of the Lat/Lon Data based on user dropdowns
colLocs[0] = ($('#Value_0 :selected').text());
colLocs[1] = ($('#Value_1 :selected').text());
colLocs[2] = ($('#Value_2 :selected').text());
colLocs[3] = ($('#Value_3 :selected').text());
LatColumn = colLocs.indexOf("Lat");
LongColumn = colLocs.indexOf("Long");
}
function AllTheSame(array) { //if they do not designate the checkboxes, I prompt them to
var first = array[0];
return array.every(function (element) {
return element === first;
});
}
This function takes all of the data in the designated columns and places them into an array for calculation.
function data2Array() {
//gets the lat and long data from the assigned columns and transfers them to an array for calculation
$("#dvCSV tr td:nth-child(" + (LatColumn + 1) + ")").each(function () {
var tdNode = $("<td/>");
tdNode.html(this.innerHTML);
LatData.push(tdNode.text());
});
LatData.splice(0, 2);
LatData.unshift(1, 1);
$("#dvCSV tr td:nth-child(" + (LongColumn + 1) + ")").each(function () {
var tdNode = $("<td/>");
tdNode.html(this.innerHTML);
LongData.push(tdNode.text());
});
LongData.splice(0, 2); //these two lines remove the first two items then replace them with 0
LongData.unshift(1, 1);
}
The first of these functions removes the checkbox column after calculations are done then new calculated columns are appended at the end. The second one was my attempt to read the checkboxes into an array. Ideally I'd want an array of values true or false, then do the calculations and return the calculated values back to the dvCSV table. For the td's where no calculation was performed, the cell would be empty.
function removeChecks() {
$("#dvCSV th:last-child, #dvCSV td:last-child").remove();
}
function makeCheckArray() {
var searchIDs = $("#dvCSV tbody td:last() input:checkbox:checked").map(function () {
return $(this).val();
}).get();
alert(searchIDs);
}
Hopefully I made the problem clear. Any help would be appreciated.
Pass a class when your table is generated into the tr element. Then create an on change method for your checkboxes. Read more here: http://api.jquery.com/on/
Also if you cannot get the inserted rows id's from your table then start a counter outside of your js like this
counter = 0;
Then inside of your loop add counter++
SO..
<tr class="row-1">
<td>
</td>
</tr>
Then add this snippet outside all of your other JS
$( "tr" ).on( "change", function() {
//do something
$(this+'.row-'+(counter)).hide();
});
This should get you headed in the right direction.

Jquery each only adds the first elements

I have a form where i can select a product then set a begin week (for example 1) and a end week (for example 10)
Then i have a table with 52 rows that represent the weeks. I want when a user selects a product and set the weeks it adds the product in the table on the set weeks.
Everything works fine when i add week 1 - 10 but when i put 3 - 10 it doesnt work.
Here is my Jquery code
$(".sub_product_toevoegen").click(function(e) {
e.preventDefault();
var product = $("select[name='select_product'] option:selected").val();
var start_week = $("input[name='start_week']").val();
var eind_week = $("input[name='eind_week']").val();
$(".tabs .nieuwe_offerte_table tbody tr td a.product_toevoegen").each(function(index) {
for (i = start_week; i <= eind_week; i++) {
if (i == index + 1) {
$(this).append(product);
}
}
});
});
Someone can tell me what im doing wrong ?
Try changing famous each function to this:
$(".tabs .nieuwe_offerte_table tbody tr td a.product_toevoegen").slice(start_week-1, eind_week).append(product);

creating a 2 column table dynamically using jquery

I am trying to generate a table dynamically using ajax call. To simplify things i have just added my code to js fiddle here -> http://jsfiddle.net/5yLrE/81/
As you click on the button "HI" first two columns are created properly.. but some how as the td length reaches 2 . its not creating another row. The reason is that when i do find on the table elements its actually retrieving the children table elements. Can some one pls help.
I want a two column table.. Thank you.
sample code:
var tr = $("#maintable tbody tr:first");
if(!tr.length || tr.find("td:first").length >= max) {
$("#maintable").append("<tr>");
}
if(count==0) {
$("#maintable tr:last").append("<td>hi"+content+"</td>");
}
Basically the matching of descendants was allowing for great great grandchildren etc. Just needed to make the matching more specific.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/5yLrE/91/
max = 2
$("button").click(function () {
var content = $('#template').html();
var $table = $("#maintable");
var tr = $table.find(">tbody>tr:last");
if (!tr.length || tr.find(">td").length >= max) {
// Append a blank row
tr = $("<tr>");
$table.append(tr);
}
tr.append("<td>hi " + content + "</td>");
});
This one always targets the last row and adds a row if it does not exists at all (or there are too many divs already) which is what I gather you intended.
I also used the templating I suggested to separate messy HTML strings from the code.
You will want to check the length of the table cells before incrementing a new table row. After you have reached your max column length, reset the row and start over.
JSFiddle
max_columns = 2;
count=0;
$("button").click(function() {
var content='column';
if(count==max_columns||!$('#maintable tr').length){
$("#maintable").append("<tr>");
count=0;
}
if(count!=max_columns)
$("#maintable tr:last").append("<td>"+content+"</td>");
else
$("#maintable tr:first").append("<td>"+content+"</td>");
count++;
});

Use Javascript to scroll in HTML tables?

I have a few table in a scrollbox. Upon loading the page I would like it to automatically scroll to the first empty table row using Javascript. Is this possible?
$("table tr").each(function() {
var cell = $.trim($(this).find('td').text());
if (cell.length == 0){
var el = cell;
el.scrollIntoView(true);
}
Once you have the empty row, you can scroll to it like this.
function scrollIntoView(el){
window.scrollTop( el.offset().top - ($(window).height()/2) );
}

Copying Dynamic Table Column with rows of Hidden style properties to textarea jQuery

I'm pretty new to jQuery and I'm having a little trouble accomplishing a specific function that I want for my table.
I have a db list that gets dynamically sorted and I want to be able to create a textarea that includes the text from a specific column on the click of the column header. I have some of the functionality from the code that I used from this http://jsfiddle.net/4BwGG/3/ but here are some things I just can't figure out:
I have some of the rows in my table hidden using style="display: none" property within the <tr> tag and when the script parses everything, the information from those hidden rows get included too. How do I do a check so that only the displayed rows are copied to the text area?
Here is what one row entry looks like:
<tr filtermatch="false" style="display: none;">
<td>< a href="http://example.edu">Tommy Trojan< /a>< /td>
< td>123-555-1231< /td>
< td>Statue Man< /td>
< td>[LTS1] [LTS2] [PM] [PM2] [TA1] [TA2] < /td>
< td>tommy#example.edu< /td>
< /tr>`
Here is the Function:
function SelectColumn(index, tableId) {
var columnText = 'You selected:\n\n';
var columnSelector = '#' + tableId + ' tbody > tr > td:nth-child(' + (index + 1) + ')';
var cells = $(columnSelector);
// clear existing selections
if (window.getSelection) { // all browsers, except IE before version 9
window.getSelection().removeAllRanges();
}
if (document.createRange) {
cells.each(function(i, cell) {
var rangeObj = document.createRange();
rangeObj.selectNodeContents(cell);
window.getSelection().addRange(rangeObj);
columnText = columnText + '\n' + rangeObj.toString();
});
}
else { // Internet Explorer before version 9
cells.each(function(i, cell) {
var rangeObj = document.body.createTextRange();
rangeObj.moveToElementText(cell);
rangeObj.select();
columnText = columnText + '\n' + rangeObj.toString();
});
}
alert(columnText);
}
Try wrapping the code in a conditional statement that checks the visibility of the tr.
For example:
if (document.createRange) {
cells.each(function(i, cell) {
if ($(cell).closest('tr').is(':visible')) {
var rangeObj = document.createRange();
rangeObj.selectNodeContents(cell);
window.getSelection().addRange(rangeObj);
columnText = columnText + '\n' + rangeObj.toString();
}
});
}
Of course, you'd want to do the same thing in the else block as well. But for the record, that jsFiddle did not work for me in IE7 (it throws an error about unsupported property or method).
I know you didn't ask, but unless you need the column to actually be selected, I would refactor the code. If you want the column to appear selected, I'd probably add a little CSS.
Someone else could probably improve the code even more. But here is my suggestion. I've added comments to explain what I did and why.
function SelectColumn(index, tableId) {
// cache the table selector in a local variable
// because we are going to use it more than once
var columnText = 'You selected:\n\n',
table = $('#' + tableId),
cells = table.find('td:nth-child(' + (index + 1) + ')');
// reset the background color of all cells
table.find('td').css('background-color', '#fff');
cells.each(function(i, cell) {
// turn cell into a jQuery object and cache it
// because we are going to use it more than once
cell = $(cell);
if (cell.closest('tr').is(':visible')) {
// get the cell text and trim it
// because different browsers treat newlines differently
columnText += $.trim(cell.text()) + '\n';
// set a background color on the selected cells
cell.css('background-color', '#ccc');
}
});
alert(columnText);
}
If you are using jquery it will make things very easy.
To select only visible elements you can use :visible in jquery.
$(document).ready(function(){
var textAreaContent=[];
$('tr:visible').each(function(){
var content=$('<div />').append($(this).clone()).html();
textAreaContent.push(content);
});
$('.textarea').val(textAreaContent.join(''));
});
check on jsfiddle http://jsfiddle.net/sudhanshu414/9YeLm/
Other option of selecting is using filter. This can also be useful if you want to filter on some other condition.
$(document).ready(function(){
var textAreaContent=[];
$('tr').filter(function(){ return $(this).css('display')!='none';}).each(function(){
var content=$('<div />').append($(this).clone()).html();
textAreaContent.push(content);
});
$('.textarea').val(textAreaContent.join(''));
});
Jsfiddle : http://jsfiddle.net/sudhanshu414/3GfqN/

Categories