Show total no. rows for in HTML <span> - javascript

I need your help in displaying the total number of rows for the available tables in the appropriate span. There are 3 tables and I want the below code to show the total no. of rows in the first table in span1 & the total no. of rows for the second table in span2.
The JavaScript is:
function count() {
var tables = document.getElementsByClassName("tablesorter");
var rows;
var span = Array();
for (var i = 0; i < tables.length; i++) {
rows = tables[i].rows.length-1;
alert(rows);
alert(span[i]);
span[i].innerHTML = rows;
}
}
However, span[i] is not picking up the value and print it in the HTML span.
The HTML code is:
<body>
<span id="span1"></span>
<span id="span2"></span>
<span id="span3"></span>
</body>
I am looking forward your assistant and help.

Use this function instead:
function count() {
var tables = document.getElementsByClassName("tablesorter");
var rows;
for (var i = 0; i < tables.length; i++) {
rows = tables[i].rows.length-1;
alert(rows);
document.getElementById("span" + (i + 1)).innerHTML = rows;
}
}
You are never referring to the span, so that is why I used
document.getElementById("span" + (i + 1)).innerHTML = rows;

Related

how to find a td by index in jquery

how can i change the inner html by getting element by index
i want to change the content of cells according to their index values
<table>
<tr><td></td><td></td></tr>
<tr><td></td><td></td></tr>
<tr><td></td><td></td></tr>
</table>
function LFLS() {
// LFLS => load from local Storage
for (i = 0; i < localStorage.length; i++) {
key = localStorage.key(i);//it return values like ("1,2","2,5", etc.)
console.log(key)
row = key.split(",")[0];
col = key.split(",")[1];
//how to get the cell by row and col
}
}
As Sakil said you can use eq(). Try this:
function LFLS() {
// load from local Storage
for (i = 0; i < localStorage.length; i++) {
key = localStorage.key(i);
row = key.split(",")[0];
col = key.split(",")[1];
// how to get the cell by row and col
$("table tr").eq(row).children().eq(col).html('NEW VALUE')
}
}
I believe you need the following snippets.
Before your for loop
const rows = $("table tr");
After you obtain row & col variables
const cellToUpdate = rows[row].children[col];
Alternatively, if you're looking to programatically loop through the table you could use the following snippet.
<script type="text/javascript">
const rows = $("table tr");
for( i = 0; i < rows.length; i++ ) {
const currRow = rows[i];
const rowChildren = currRow.children;
for( n = 0; n < rowChildren.length; n++ ) {
const cell = rowChildren[n];
cell.innerHTML = "My new data for row: " + i + " in cell " + n;
}
}
</script>
Is something on the lines of below not going to work for you for some reason?
$("table tr:nth-of-type([your-row])).eq([your-col]).html([your_content]);

Create table of specified column and rows in Jquery

I am new to jQuery, I want to create table with specific number of rows and columns in jQuery.
Here is what I tried this creates table with specific number of rows but it doesn't create table of specific number of columns
function constructTable () {
let table = $('<table>').first().prepend('<caption><b> Borrow </b></caption>');
let row;
let cell1;
let cell2;
table.attr({"id":"burrow"});
for(i=0; i < 3; i++) {
row = $('<tr>');
table.append(row);
}
for ( i = 0 ; i < 4; i++ ) {
cell1 = $('<td>').text('cell ' + i);
row.append(cell1);
}
$("#borrowLicensediv").append(table);
document.getElementById('borrowLicensediv').style.display = '';
}
<!doctype html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body onload="constructTable ()" style="background: white;">
<div id="borrowLicensediv" style="display: none; margin-top:10px; margin-bottom:25px; margin-left:20px; margin-right:37px;"></div>
</body>
</html>
Before you append rows to the table these must first have cells otherwise you're going to have empty rows in your table with no columns. Leaving jQuery aside for a moment, the general problem is:
Build a row
Append it to the table
Repeat 1 and 2 for all rows to add
Step (1) implies that you first create the cells you want in the row and add them to the row. This means you're going to have nested loops (whereas in your example they're inline).
You need something more like
for(i=0; i < 3; i++) {
var row = "<tr>";
for ( j = 0 ; j < 4; j++ ) {
var value = "cell " + i + "," + j;
var td = "<td>" + value + "</td>";
row += td;
}
row += "</tr>";
table.append(row);
}
You are adding the TDs to the last Row because your cell loop is outside of the Row loop. We need to move the loop inside and fix the iterator variable, like this:
for(var r=0; r < 3; r++) {
row = $('<tr>');
for ( var c = 0 ; c < 4; c++ ) {
cell = $('<td>').text('cell ' + r+c);
row.append(cell);
}
table.append(row);
}

Javascript only: Function renders a dropdown and table where the value from the dropdown is needed to filter the table

I created a function which renders a dropdown and a table. This dropdown gives me values which I use inside the function to filter the table. For some reason, it does not update when I reselect something on the dropdown.
No frameworks please thank you!
Here are some screenshots:
It does not update the columns showed because when I console.log() the values from the dropdown it does not update. It still says 1 5 but when I click the second one it should say 2 5.
I selected the second option on the dropdown. I have no idea how to do this. Sorry, I'm a beginner.
//function which we will use to hide and unhide rows
function toggleClass(element, className, toSet) {
element.classList[toSet ? 'add' : 'remove'](className);
}
//The table is already rendered and when the buttons on the screen are clicked, this pagination function is called
function columnPagination(input) {
var table = document.getElementById("tablePrint"),
dataRows = table.getElementsByTagName('tr'),
listHTML = "";
//get date labels for dropdown
var filterDateLabels = [];
var columns = table.getElementsByTagName('th');
for(var ii = 0; ii < columns.length; ii++){
if(ii%input==0){
filterDateLabels.push(columns[ii].innerHTML.slice(21,33));
}
if(ii%input==input-1){
filterDateLabels.push(columns[ii].innerHTML.slice(21,33));
}
}
//display dropdown with values which you will use to filter the table
listHTML += "<select id=\"pagenumber\")>";
for(var ii = 0; ii < filterDateLabels.length; ii++){
listHTML += "<option value = \"" + ii + "\">" + filterDateLabels[ii] + " - ";
if(filterDateLabels[ii+1]!= ""){
listHTML += filterDateLabels[ii+1] + "</option>";
ii++;
}
else{
listHTML+="LAST </select>";
}
}
document.getElementById('dates').innerHTML = listHTML;
var multiplier = document.getElementById('pagenumber').value;
multiplier = multiplier/2;
if(multiplier == 0){
multiplier = 1;
}
//hiding function which works but doesn't update when the dropdown is clicked
input = input*multiplier;
console.log(multiplier, input);
for (var i = 0; i < dataRows.length; i++) {
var cells = dataRows[i].children;
for (var cell = 0; cell < cells.length; cell++) {
toggleClass(cells[cell], 'hide', cell > input)
}
}
}
I ended up just using onchange="myFunction()".
http://www.w3schools.com/jsref/event_onchange.asp
Everything you need is up there if you encounter the same issue as I did. I was having trouble because I was editing the wrong file. #KevinKloet helped me realize that by pointing out another error. Thanks!

jQuery, adding multiple table rows is not working correctly

The idea is to build a function that takes an input and uses that to build a grid. I'm trying to establish the grid functionality first, and I'm having a peculiar error. I searched for a few hours, but the answers all tell me that a simple "append" should be working.
The specific error that I am getting:
When I load up the webpage, it is only adding one table row to the tbody, and only one table data to that table row. The idea is instead to create a grid of 16 x 16, with 16 rows and 16 data. Console logs show that the loops are all working correctly.
The html is just a basic file that imports the javascript correctly (All tested) with a simple:
div class="container" /div
Code:
$(document).ready(function(){
$(".container").html("");
/*this function makes a table of size numRow and
num data. it then gives each data element
*/
//blank rows to insert
var blankResults = $("<table>");
var result = blankResults;
var row = $("<tr/>");
var data = $("<td/>");
function makeTable(num)
{
result = blankResults;
//create num rows
for (var i = 0; i < num; i++)
{
//for each row
//add data num times
for (var j = 0; j < num; j++)
{
console.log(j);
row.append(data);
}
//append row
console.log(i);
result.append(row);
}
}
//starting area
makeTable(16);
$(".container").append(result);
//Start with 16 by 16 of square divs -
//put inside a container div
});
Try this code.
$(document).ready(function(){
$(".container").html("");
/*this function makes a table of size numRow and
num data. it then gives each data element
*/
function makeTable(num)
{
var output = '<table>';
//create num rows
for (var i = 0; i < num; i++)
{
//for each row
output+= '<tr>'
for (var j = 0; j < num; j++)
{
output += '<td></td>';
}
output += '</tr>';
}
output += '</table>';
return output;
}
//starting area
var result = makeTable(16);
$(".container").append(result);
//Start with 16 by 16 of square divs -
//put inside a container div
});
You are appending to the same variables all the time...row and 'data`. you should not do that.
As you can see from the code below, you need to create the var row = $("<tr>"); on each loop, to reference it when you append the <td> (table cell) to that newly created row.
Modifed to use only one loop:
$(document).ready(function(){
function makeTable(num) {
var table = $("<table>"), row;
for (var i = 0; i < num; i++){
row = $("<tr>");
table.append(row);
row.append(Array(num + 1).join("<td></td>"));
}
return table;
}
$(".container").html(makeTable(16));
});
DEMO PLAYGROUND
Of course, this is not a good way generating a table. running jQuery function on each loop is slow and bad practice. You should generate a big string which will represent your DOM structure and then append that string where needed and jQuery will make a DOM node out of it.
I made up my own html for this but it should be as simple as using two nested for loops grabbing values the size input. Here's what I came up with:
$("#tableMaker").click(function () {
$('.container').html("");
$('.container').append("<table></table>");
for (var i = 0; i < $('#size').val(); i++) {
$('table').append("<tr></tr>");
for (var j = 0; j < $('#size').val(); j++) {
$('tr:last').append("<td>Column " + (j+1) + ", Row " + (i+1) + "</td>");
}
}
})
td {
border: black solid 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="size" placeholder="Size" />
<button id="tableMaker" type="button">Generate Table</button>
<br />
<div class="container">
<div />

Concatenate loop within loop in jQuery?

I am trying to create a grid like structure. I want to create a loop within a loop and append divs based on if it is a column or a row. Below is my attempt:
for (var row = 0; row < 8; row++) {
$('#board').append('<div class="row">'+ row +'</div>');
}
What I would like to replicate in plain Javascript (code is most likely incorrect, I just want to show an example of what I want):
var board = document.getElementById('board');
for (var row = 0; row < 8; row++) {
board.write('<div class="row">');
for(var col = 0; col < 8; col++) {
var row = document.getElementsByClassName('row');
row.write('<div class="piece">'+col+'</div>')
}
board.write('</div>');
}
It would be useful if I could somehow replicate the document.write() method in jQuery. .append() did not work correctly for me when I tried to include a forloop.
You just need to loop through rows and then cells to build a single html string and than append it only once:
var rows = [], cells = [];
for (var row = 0; row < 8; row++) {
cells = [];
for (var cell = 0; cell < 8; cell++) {
cells.push('<div class="piece">'+ row +'</div>');
}
rows.push('<div class="row">' + cells.join('') + '</div>');
}
$('#board').html(rows.join(''));
DEMO HERE
What I understand you want to end up with a structure like this:
<div id="board">
<div class="row">
<div class="piece"></div>
<div class="piece"></div>
<div class="piece"></div>
(...)
</div>
(...)
</div>
Let's assume you already have a board (<div id="board"></div>).
for( var row = 0; row < 8; row++ ) {
//Create a row
$row = $('<div class="row"></div>');
//Stuff 8 pieces in that row
for( var col = 0; col < 8; col++ ) {
$row.append( $('<div class="piece">' + col + '</div>') );
}
//Add the row to the board
$('#board').append( $row );
}
Edit: In your case you can even simplify it to:
//Stuff 8 rows in the board
for( var row = 0; row < 8; row++ ) {
$('#board').append( $('<div class="row"></div>') );
}
//Stuff 8 pieces in every of the 8 rows
//This can be done because the piece is the same for every row
for( var col = 0; col < 8; col++ ) {
$('.row').append( $('<div class="piece">' + col + '</div>') );
}
jsFiddle: http://jsfiddle.net/3jGnF/
Try the following - if you need to manipulate DOM more specifically, then use JQuery
var board = document.getElementById('board'),
html = '';
for (var row = 0; row < 8; row++) {
html += '<div class="row">';
for(var col = 0; col < 8; col++) {
html += '<div class="piece">'+col+'</div>';
}
html += '</div>';
}
board.innerHTML = html;
Or with JQuery:
var board = $('#board');
...
board.append($(html));

Categories

Resources