Please take a look at this fiddle example. I'm adding new columns using AJAX on click. Is there a way to count the columns of the table and limit the number of new columns to 6? Could anyone give me suggestions?
jQuery:
$(function () {
var ajaxfunction = function(){
$('.area').on("click","button", function(){
var source = $(this).data('feed');
$.ajax({
url: source,
success: function (data) {
$(data.query.results.json.json).each(function (index, item) {
var title = item.title,
year = item.year,
job = item.Job,
education = item.Education,
background = item.Background,
ingredient = item.Ingredient;
$('#header').after('<th>'+title+'</th>')
$('#ingredient').after('<td>'+ingredient+'</td>')
$('#year').after('<td>'+year+'</td>')
$('#background').after('<td>'+background+'</td>')
$('#education').after('<td>'+education+'</td>')
$('#job').after('<td>'+job+'</td>')
});
$('#toptable').stickyTableHeaders(); //Fixed Header Plugin
},
});
});
}
ajaxfunction();
});
HTML
<div class="area">
<button>Class B</button>
<button>Class C</button>
<button>Class D</button>
</div>
<table id="toptable">
<thead>
<tr>
<th id="header" style="visibility:hidden">-</th>
</tr>
</thead>
<tbody>
<tr>
<td id="ingredient">Ingredient</td>
</tr>
<tr>
<td id="year">Year</td>
</tr>
<tr>
<td id="background">Background</td>
</tr>
<tr>
<td id="education">Education</td>
</tr>
<tr>
<td id="job">Job</td>
</tr>
</tbody>
</table>
Get Column Count (If you start using colspans this will need to change to reflect that):
var colcount = $("#toptable").find("tr:first th").length; or
var colcount = $("tr:first th", "#toptable").length; or
var colcount = $("#toptable tr:first th").length;
Limit the number of columns (tested and working):
$('.area').on("click","button", function(){
var colspan = $("#toptable tr:first th").length;
alert("Current number of Columns = " + colspan);
if(colspan > 6)
{
alert("Too Many Columns");
return false;
}
var source = $(this).data('feed');
//the rest of your code
});
See this working Fiddle
NOTE: Because you are adding columns on an Ajax Success result, the column count is only true at the time of the click event. This means that the column count could be more once the Ajax Response arrives. You need to either cancel the request if there is an Ajax call in progress, or redesign so that you're not making so many HTTP calls (which is bad practice anyway, something like 68% of all performance improvements on the web are found in reducing HTTP calls.)
Related
I'm working on a small userscript to sort a table, the structure of the table is really weird however. What i'm trying to do is to add an extra sort feature so I can sort on the ranking (#) of the persons.
Table data looks like this:
<table id="outer">
<tr>
<td><div id="bgn"></div></td>
<td>User 1</td>
<td>
<table id="inner">
<tbody>
<tr>
<td>Rank</td>
<td id="tdp">#28</td>
</tr>
</tbody>
</table>
</td>
</tr>
<!-- more rows -->
</table>
There are some additional <td>'s but they are not important right now. There are about 52 rows, but these could vary, of course.
Current jQuery code I have:
jQuery( document ).ready(function() {
var rankings = [];
$(document).on('click', '#tdr', function() {
// skipping first line because it's the header
$('tr:not(:first-child').each(function () {
var rank = $(this).find('#tdp').text();
var rank2 = rank.substring(1, rank.length)
rankings.push(rank2);
});
console.log(rankings.sort(sortNumber));
});
function sortNumber(num1, num2) {
return num1 - num2;
}
});
JS Bin Example
The output in the console is a correctly sorted array with all the rankings, I just don't have any idea how to also swap the corresponding <tr>'s so that the table get's rebuild the right way. Looking for any tips or pointers!
This suggestion is not really into "sorting" the rows, but re-constructing the table with the sorted rows. But this should do the job:
rankings = rankings.sort(sortNumber);
var table = $('<table></table>');
for (var i = 0; i < rankings.length; i++) {
var row = $('tr').filter(function() {
var rank = $(this).find('#tdp').text();
return rank.substring(1, rank.length) == i;
});
table.append(row);
}
$('#originalTable').html(table.html());
I have a html table that looks like this...
<table>
<tr>
<th>Date</th>
<th>Pair</th>
<th>Game</th>
<th>Chance</th>
</tr>
<tr>
<td>2014-2-12</td>
<td>Milan-Udinese</td>
<td>1</td>
<td>1.6</td>
</tr>
<tr>
<td>2014-2-13</td>
<td>Juventus-Inter</td>
<td>x</td>
<td>2.5</td>
</tr>
<tr>
<td>2014-2-13</td>
<td>Arsenal-Liverpul</td>
<td>2</td>
<td>2.5</td>
</tr>
</table>
<p>Total number is:MULTIPLICATION OF ALL CHANCE COLUMN TD</p>
all my rows are added dynamically,how do i multiply all chance column td values(numbers)?Do i have to put certain class on chance tds and then get all tds with that class,and loop through and multiply every value then?I'm kinda a newbie so any help would be appreciated.
You can either do something like this:
var tots = 1;
$('tr td:nth-child(4)').each(function(){
tots *= $(this).text();
});
the nth-child(4) is selecting the fourth td in each row, if you want another, just change that number.
or you can give the cells you want to multiple classes, like you said.
example here
If you're using jQuery, the :last-child selector could be helpful.
<p>Total number is: <span id="result"></span></p>
Javascript:
res = 1;
$("tr td:last-child").each(function() {
res *= parseFloat($(this).html());
});
$("#result").html(res);
Have a look to this JSFiddle.
You don't need jQuery to do this. querySelectorAll supports nth-child selector as well.
var derp = document.querySelectorAll("tr td:nth-child(4)");
var total = 1;
var results = [].reduce.call(derp, function (prev, next) {
return prev * ( + next.textContent );
});
Grab the element, and use native Array prototype methods ([]) to iterate the NodeList and return the parsed value of the element, then return the multiplied total.
Here is a fiddle for you.
$(function () {
var chanceTotals = 1;
$("tr td:nth-child(4)").each(function () {
chanceTotals *= parseFloat($(this).html());
});
$("#totals").html("Total number is: " + chanceTotals);
});
Using jQuery, this executes an anonymous function when the document is ready that will do the calculation for you.
You will need to add the id totals to your p element in order for this to work.
Look at this JSFiddle
You really do not need jquery at all to do this. Interacting with the DOM directly may make you write more (browser support), but it can be more efficient than using jQuery (Unnecessary overhead).
As you can see, I restructured your <table>. I could have just grabbed the <tbody> and looped over its children and skipped the whole if <TD> ? check.
DEMO
$(document).ready(function () {
var table = $('#myTable').get(0);
var multiplier = 1;
var col = 3;
for (var row = 0; row < 4; row++) {
var cell = table.rows[row].cells[col];
if (cell.nodeName == 'TD') {
var text = cell.innerText || cell.textContent;
multiplier *= parseFloat(text);
}
}
$('#multiplier').text(multiplier);
});
<table id="myTable">
<thead>
<tr>
<th>Date</th>
<th>Pair</th>
<th>Game</th>
<th>Chance</th>
</tr>
</thead>
<tbody>
<tr>
<td>2014-2-12</td>
<td>Milan-Udinese</td>
<td>1</td>
<td>1.6</td>
</tr>
<tr>
<td>2014-2-13</td>
<td>Juventus-Inter</td>
<td>x</td>
<td>2.5</td>
</tr>
<tr>
<td>2014-2-13</td>
<td>Arsenal-Liverpul</td>
<td>2</td>
<td>2.5</td>
</tr>
</tbody>
</table>
<p>Total number is:
<span id="multiplier">MULTIPLICATION OF ALL CHANCE COLUMN TD</span>
</p>
I'm trying to create a show/hide function for data within a table populated with data from a mssql database. The function should look for rows with the same value in the "capability" column and onclick, hide all rows with the same value. After this, a row is inserted into the table with the same capability value, but summarizes the data in the hidden rows. This should work in the way that grouping cells together works in excel.
I've managed to get this to work, but it only works for the first click and I receive a "cannot read innerHTML property of NULL" for any of the function's calls after that.
function compactRows(thisrow) {
var totalRows = document.getElementById("DataTable").getElementsByTagName("tr").length;
var summaryVal1= [];
var summaryVal2= [];
for(var i = 1; i < totalRows;i++) {
var trID = "capability" + i;
if(thisrow.innerHTML == document.getElementById(trID).innerHTML) { //The error gets returned on this line
summaryVal1.push(document.getElementById(trID).parentNode.children[5].innerHTML);
summaryVal2.push(document.getElementById(trID).parentNode.children[14].innerHTML);
document.getElementById(trID).parentNode.style.display = 'none';
}
}
createNewRow(thisrow, summaryVal1, summaryVal2);
}
//I took out the logic for the data summarizing in the createNewRow function because I don't think its relevant to the issue I'm having. Also, I didn't want to crowd the area with unrelated code
function createNewRow(row, ibxMobile, overallStatus) {
var table = document.getElementById("DataTable");
var localRow = table.insertRow(row.parentNode.rowIndex);
var cell1 = localRow.insertCell(0);
cell1.setAttribute("id", "entry1");
var cell2 = localRow.insertCell(0);
cell2.setAttribute("id", "Capability");
cell2.innerHTML = row.innerHTML;
var cell3 = localRow.insertCell(0);
cell3.setAttribute("id", "entry3");
}
The function called at the bottom, createNewRow, handles making the row to be entered after all the rows are hidden. It also, handles the logic for summarizing the hidden rows.
All help is greatly appreciated! Thank you
Edit 1: example table set up
<table>
<tr>
<th>Entry1 </th>
<th>Capability</th>
<th>Entry3 </th>
</tr>
<tr>
<td>1.1</td>
<td id="Capability1" onclick="compactRows(this)">Lasers</td>
<td>stuff</td>
</tr>
<tr>
<td>1.2</td>
<td id="Capability2" onclick="compactRows(this)">Lasers</td>
<td>things</td>
</tr>
<tr>
<td>2.1</td>
<td id="Capability3" onclick="compactRows(this)">Beams</td>
<td>more things</td>
</tr>
</table>
//The Below table is what it looks like after clicking either of the first two entries
<table>
<tr>
<th>Entry1 </th>
<th>Capability</th>
<th>Entry3 </th>
</tr>
<tr>
<td>1</td>
<td id="Capability">Lasers</td>
<td></td>
</tr>
<tr>
<td>2.1</td>
<td id="Capability3" onclick="compactRows(this)">Beams</td>
<td>more things</td>
</tr>
</table>
There is no "Capability1" id for any rows after the "CreateNewRow" is called. Therefore, the second time "CompactRows()" is called a null reference is thrown when accessing "document.getElementById("Capability1").innerHTML". Rework the CreateNewRow to inlcude the increment for the Capability id value or test that "getElementById" actually returns an object before attempting to access the innerHTML method.
using php to echo json array inline i want js/jquery to populate table according to these data.
HTML table
<table>
<thead>
<tr>
<th>Time</th>
<th data-day='2013-03-15'>15-3</th>
<th data-day='2013-03-16'>16-3</th>
<th data-day='2013-03-17'>17-3</th>
</tr>
</thead>
<tbody>
<tr data-time='09'>
<td>9am</td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
<script>
var arr=[
{"date":"2013-03-15","id":"4","time_booked":"09:00:00"},
{"date":"2013-03-15","id":"1","time_booked":"09:10:00"},
{"date":"2013-03-17","id":"5","time_booked":"09:30:00"}
];
$.each(arr,function(){
console.log('id:'+this.id+'inside:'+this.date+'|'+this.time_booked);
});
</script>
i want to loop thro arr and according to its date and time_booked write id inside td.
for example first row will go to td with date-day='2013-03-15' and data-time='09'
so how can i do this using javascript ?
im thinking should i include data-day,data-time inside each td in tbody ? or is there a better way to do it ?
current approach:
include data-day inside each tr so html of tbody is
<tr data-time='09'>
<td data-day='2013-03-15'></td>
<td data-day='2013-03-16'></td>
etc..
</tr>
then use js
$.each(arr,function(){
var rday=this.date;
var rtime=this.time_booked;
var sel='tr[data-hr="'+rtime.substr(0,2)+'"]';
var dom=$(sel).find('td[data-day="'+rday+'"]').first();
if(dom.length)dom.append(this.id);
});
but i have a feeling its stupid ! there must be a way to map table using x,y (table head,row head) or there is none ?
I think the jQuery index function is what you're looking for. In the code sample below, I've used it to fetch the colIndex for the date. In this case, it fetches all of the th cells within the table, and uses .index(..) with a selector seeking the required date. This gives the column index of the date you're seeking, and from there it's all pretty straight-forward.
var arr=[
{"date":"2013-03-15","id":"4","time_booked":"0900"},
{"date":"2013-03-15","id":"1","time_booked":"0910"},
{"date":"2013-03-17","id":"5","time_booked":"0930"}
];
$.each(arr,function(){
var cell = GetCellByDateAndTime(this.date, this.time_booked);
$(cell).text(this.id);
});
function GetCellByDateAndTime(date, time) {
var colIndex = $("#BookingsTable th").index($("[data-day='" + date + "']"));
var row = $("#BookingsTable tr[data-time='" + time + "']")
var cell = $(row).children($("td"))[colIndex];
return cell;
}
And a Fiddle.
I'm trying to filter table rows in an intelligent way (as opposed to just tons of code that get the job done eventually) but a rather dry of inspiration.
I have 5 columns in my table. At the top of each there is either a dropdown or a textbox with which the user may filter the table data (basically hide the rows that don't apply)
There are plenty of table filtering plugins for jQuery but none that work quite like this, and thats the complicated part :|
Here is a basic filter example http://jsfiddle.net/urf6P/3/
It uses the jquery selector :contains('some text') and :not(:contains('some text')) to decide if each row should be shown or hidden. This might get you going in a direction.
EDITED to include the HTML and javascript from the jsfiddle:
$(function() {
$('#filter1').change(function() {
$("#table td.col1:contains('" + $(this).val() + "')").parent().show();
$("#table td.col1:not(:contains('" + $(this).val() + "'))").parent().hide();
});
});
Slightly enhancing the accepted solution posted by Jeff Treuting, filtering capability can be extended to make it case insensitive. I take no credit for the original solution or even the enhancement. The idea of enhancement was lifted from a solution posted on a different SO post offered by Highway of Life.
Here it goes:
// Define a custom selector icontains instead of overriding the existing expression contains
// A global js asset file will be a good place to put this code
$.expr[':'].icontains = function(a, i, m) {
return $(a).text().toUpperCase()
.indexOf(m[3].toUpperCase()) >= 0;
};
// Now perform the filtering as suggested by #jeff
$(function() {
$('#filter1').on('keyup', function() { // changed 'change' event to 'keyup'. Add a delay if you prefer
$("#table td.col1:icontains('" + $(this).val() + "')").parent().show(); // Use our new selector icontains
$("#table td.col1:not(:icontains('" + $(this).val() + "'))").parent().hide(); // Use our new selector icontains
});
});
This may not be the best way to do it, and I'm not sure about the performance, but an option would be to tag each column (in each row) with an id starting with a column identifier and then a unique number like a record identifier.
For example, if you had a column Produce Name, and the record ID was 763, I would do something like the following:
<table id="table1">
<thead>
<tr>
<th>Artist</th>
<th>Album</th>
<th>Genre</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr>
<td id="artist-127">Red Hot Chili Peppers</td>
<td id="album-195">Californication</td>
<td id="genre-1">Rock</td>
<td id="price-195">$8.99</td>
</tr>
<tr>
<td id="artist-59">Santana</td>
<td id="album-198">Santana Live</td>
<td id="genre-1">Rock</td>
<td id="price-198">$8.99</td>
</tr>
<tr>
<td id="artist-120">Pink Floyd</td>
<td id="album-183">Dark Side Of The Moon</td>
<td id="genre-1">Rock</td>
<td id="price-183">$8.99</td>
</tr>
</tbody>
</table>
You could then use jQuery to filter based on the start of the id.
For example, if you wanted to filter by the Artist column:
var regex = /Hot/;
$('#table1').find('tbody').find('[id^=artist]').each(function() {
if (!regex.test(this.innerHTML)) {
this.parentNode.style.backgroundColor = '#ff0000';
}
});
You can filter specific column by just adding children[column number] to JQuery filter. Normally, JQuery looks for the keyword from all the columns in every row. If we wanted to filter only ColumnB on below table, we need to add childern[1] to filter as in the script below. IndexOf value -1 means search couldn't match. Anything above -1 will make the whole row visible.
ColumnA | ColumnB | ColumnC
John Doe 1968
Jane Doe 1975
Mike Nike 1990
$("#myInput").on("change", function () {
var value = $(this).val().toLowerCase();
$("#myTable tbody tr").filter(function () {
$(this).toggle($(this.children[1]).text().toLowerCase().indexOf(value) > -1)
});
});
step:1 write the following in .html file
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names..">
<table id="myTable">
<tr class="header">
<th style="width:60%;">Name</th>
<th style="width:40%;">Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Germany</td>
</tr>
<tr>
<td>Berglunds snabbkop</td>
<td>Sweden</td>
</tr>
<tr>
<td>Island Trading</td>
<td>UK</td>
</tr>
<tr>
<td>Koniglich Essen</td>
<td>Germany</td>
</tr>
</table>
step:2 write the following in .js file
function myFunction() {
// Declare variables
var input, filter, table, tr, td, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}