jQuery Datatables - Table with Subtable or Expandable Rows - javascript

my code just works perfectly but in a big data with lack of usability...
My table should work with 500-600 rows (updated in every 5 seconds)...
So therefore I want to make something similar:
http://i.stack.imgur.com/nPKtu.png
//Buttons added via photoshop.
I can't find this functionality #jQuery.
So I want to group data under 20/25 group header.
Each IP has 60-70 row.
2 column:
IP and FPS are the same for each group.
this is how my recent application looks like:
http://www11.pic-upload.de/03.06.14/rv6w1tboi1ip.png
so main question is: How to add Expand/collapse functionality to group of rows UNDER one main table.
and this is main part of JS code:
//მაგიდის ახლიდან დახატვა
function reDrawTable(){
"use strict";
$("table#content").dataTable({
"destroy" : true,
"ajax": "/json",
"tableTools": true,
"columnDefs": [
{
"render": function (data) {
var labelType, labelTitle;
if (data === 1) {
labelTitle = "ჩართულია";
labelType = " alert-success";
} else {
labelTitle = "გათიშულია";
labelType = " alert-danger";
}
return "<span class='label " + labelType + "'>" + labelTitle + "</span>";
},
"targets": 3
}
]
});
}
//მთავარი ფუნქცია
$(document).ready(function() {
//LastUpdate-ში ინახება ინფორმაციის განახლების დრო.
var table = $("table#content").dataTable(),
lastUpdate;
//პირველი გაშვება
$.getJSON("/json", function(data){
"use strict";
if (data.hasOwnProperty("data") === false) {
console.log("URL-ზე მონაცემები ცარიელია");
}
else {
console.log("პირველი პროცესი");
lastUpdate = data.lastUpdate;
reDrawTable();
calculateBar(data);
search();
}
});
//ყოველ 5 წამში ერთხელ ეშვება.
setInterval(function() {
"use strict";
$.getJSON("/json", function(data){
"use strict";
if (lastUpdate === data.lastUpdate) {
console.log("ახალი მონაცემები არ მოიძებნა");
} else if (data.hasOwnProperty("data") === false) {
$("table#content").dataTable({
"destroy" : true
});
console.log("მონაცემები არ იქნა მოწოდებული");
document.getElementById("success").style.width = 0 + "%";
document.getElementById("danger").style.width = 0 + "%";
} else {
reDrawTable();
search();
calculateBar(data);
lastUpdate = data.lastUpdate;
}
});
}, 5000);
} );

Solution:
Moved to Ext Js 5(new beautiful UI CRISP).
The ONLY enterprise js framework.

Related

Showing Progress while Child row loads

Coming again with another question :)
This time I had a requirement to show some progress while Child rows are being loaded. Since there is an Api call which relatively takes little time to return data, I do want to show the some progress unless the user who clicks the parent row is totally unaware whether there is a call done to see its child rows.
What I have done:
I wrote a style sheet class which has a
loader-small.gif
image as this:
tr.loading td.details-control {
background: url('/Images/loader-small.gif') no-repeat center center;
}
and applied like this:
$('#accountManagerEarningsDataTable tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row(tr);
try {
if (row.child.isShown()) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
//Calling the loading Class ------>
tr.addClass('loading');
// Open this row
var arrForTable1 = [];
var arrForTable2 = [];
totalBrokerage = 0;
totalRetailBrokerage = 0;
totalSelfServiceBrokerage = 0;
console.log('You selected: ' + row.data().AccountManagerID);
var settings = {
"columnDefs": [
{ targets: 1, align: "right", decimals: 0 },
{ targets: 2, align: "right", decimals: 0 },
{ targets: 3, align: "right", decimals: 0 },
{ targets: 4, align: "right", decimals: 2 },
{ targets: 5, align: "right", decimals: 2 }
]
};
//problems with asynchoronus call back
var response = organization_GetAccountManagerDetailEarningsAccountData(row.data(), purl2, pcontext);
if (response.success === "true") {
for (var i = 0; i < response.value.length; i++) {
for (var j = 0; j < response.value[i].Securities.length; j++) {
var itemRow2 = {};
itemRow2["Security ID"] = response.value[i].Securities[j].SecurityId;
itemRow2["Trades"] = response.value[i].Securities[j].Trades;
itemRow2["Buy Qty"] = response.value[i].Securities[j].BuyQuantity;
itemRow2["Sell Qty"] = response.value[i].Securities[j].SellQuantity;
itemRow2["Total Brkg"] = response.value[i].Securities[j].Effective_Brokerage;
itemRow2["Online Brkg"] = response.value[i].Securities[j].Online_Brokerage;
arrForTable2.push(itemRow2);
totalBrokerage = totalBrokerage + parseFloat(response.value[i].Securities[j].Effective_Brokerage);
totalSelfServiceBrokerage = totalSelfServiceBrokerage + parseFloat(response.value[i].Securities[j].Online_Brokerage);
}
totalBrokerage = Math.round(totalBrokerage * 100) / 100;
totalSelfServiceBrokerage = Math.round(totalSelfServiceBrokerage * 100) / 100;
totalRetailBrokerage = Math.round(totalRetailBrokerage * 100) / 100;
var itemRow1 = {};
itemRow1["Account ID"] = response.value[i].AccountId;
itemRow1["Account Name"] = response.value[i].AccountName;
itemRow1["..."] = '<div class="alert alert-info" role="alert">' + buildHtmlTable(arrForTable2, 'table2x' + j, settings) + '<p>Total Brokerage ' + numberWithCommas(totalBrokerage) + '</p></div>';
arrForTable1.push(itemRow1);
arrForTable2 = [];
totalBrokerage = 0;
totalRetailBrokerage = 0;
totalSelfServiceBrokerage = 0;
}
tr.removeClass('loading');
htmlTable1 = buildHtmlTable(arrForTable1, 'table1x' + i);
row.child(htmlTable1).show();
tr.addClass('shown');
}
else {
row.child('<table><tr><td>' + response.value[0].AccountId + '</td></tr></table>').show();
tr.addClass('shown');
};
}
} catch (e) {
console.log(e.message);
}
});
The Problem:
Firefox nicely shows the Progress image after the user clicks it, but Edge and Chrome does not show. Both browsers crossed this piece of code when I was debugging from developer tools of the respective browser.
Its browser compatible problem? Is there a solution for it? Help me please.
In case of chrome there is such an issue while showing the loading bar while making a server call. Please make the following changes where you are making the service call. First add the class loading to the table
tr.addClass('loading');
After that make the service call by giving a timeout function
setTimeout(function(){
var response = organization_GetAccountManagerDetailEarningsAccountData(row.data(), purl2, pcontext);
......
//Your service calls and response call backs
},1);
On providing a timeout (say 1ms), Chrome will get the time to bind the loading bar to DOM, In other case the DOM Object is not available to show the spinner.

Why can't I run my code in a browser or JS Fiddle?

With full disclosure, I am brand new to JS. I don't fully comprehend the nature of the language (e.g. is it written in html, what is the difference between JS and html?). So needless to say, I am a novice. That being said, I'm trying to build an experiment in jspsych and I went through the tutorials, tried to run the sample code, and got "Invalid JavaScript Code." I cannot find any answers to why this is. It neither works in a browser or on JS Fiddle's testing software. I would appreciate any help with this.
P.S. I'm a decent programmer in Python, and the JS syntax seems pretty straight forward, but I'm out to sea when it comes to formatting, etc.
<html>
<head>
<title>My experiment</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="jspsych-5.0.3/jspsych.js"></script>
<script src="jspsych-5.0.3/plugins/jspsych-text.js"></script>
<script src="jspsych-5.0.3/plugins/jspysch-single-stim.js"></script>
<link href="jspsych-5.0.3/css/jspsych.css" rel="stylesheet" type="text/css"></link>
</head>
<body>
</body>
<script>
/* define welcome message block */
var welcome_block = {
type: "text"
text: "Welcome to the experiment. Press any key to begin."
};
/*define instructions block*/
var instructions_block = {
type:"text",
text:"<p>In this experiment,a circle will appear in the center" +
"of the screen.</p><p>If the circle is <strong>blue</strong>," +
"press the letter F on the keyboard as fast as you can.</p>" +
"<p>If the circle is <strong>orange</strong>, do not press " +
"any key.</p>"+
"<div class ='left center-conten'><img src='img/blue.png'></img>" +
"<p class = 'small'><strong>Press the F key</strong></p></div>" +
"div class='right center-content'><img src='img/orang.png'></img>" +
"<p class='small'><strong>Do not press a key</strong></p></div>" +
"<p>Press any key to begin.</p>"
timing_post_trial: 2000
};
var test_stimuli = [
{
stimulus: 'img/blue.png',
data: { response: 'go'}
},
{
stimulus: 'img/orange.png',
data: { response: 'no-go'}
}
];
var all_trials = jsPsych.randomization.repeat(test_stimuli,10);
var post_trial_gap = function() {
return Math.floor( math.random() * 1500) + 750;
}
var test_block = {
type: 'single-stim',
choices: ['F'],
timing_response: 1500,
timing_post_trial: post_trial_gap,
on_finish: function(data){
var correct = false;
if(data.response == 'go' && data.rt > -1){
correct = true;
} else if(data.response == 'no-go' && data.rt == -1){
correct = true;
}
jsPsych.data.addDataToLastTrial({correct: correct});
},
timeline: all_trials
};
/*define debrief block*/
function getSubjectData() {
var trials = jsPsych.data.getTrialsofType('single-stim');
var sum_rt = 0;
var correct_trial_count = 0;
var correct_rt_count = 0;
for (var i = 0; i < trials.length; i++) {
if (trials[i].correct == true) {
correct_trial_count++;
if(trials[i].rt > -1){
sum_rt += trials[i].rt;
correct_rt_count++;
}
}
}
return {
rt: Math.floor(sum_rt/correct_rt_count),
accuracy: Math.floor(correct_trial_count / trials.length * 100)
}
}
var debrief_block = {
type: "text",
text: function() {
var subject_data = getSubjectData();
return"<p>You responded correctly on "+subject_data.accuracy+"% of "+
"the trials.</p><p>Your average response time was <strong>"+
subject_data.rt + "ms</strong>. Press any key to complete the "+
"experiment. Thank you!</p>";
}
};
/*create experiment timeline array*/
var timeline = [];
timeline.push(welcome_block);
timeline.push(instructions_block);
timeline.push(test_block);
timeline.pysh(debrief_block)
/*start the experiment*/
jsPsych.init({
experiment_structure: experiment,
on_finish: function() {
jsPsych.data.displayData();
}
});
</script>
</html>
Did you update the code posted here on SO? It looks like you still have some missing commas as I have indicated here with "//<-- YOU NEED A COMMA HERE". See below:
var welcome_block = {
type: "text", //<-- YOU NEED A COMMA HERE
text: "Welcome to the experiment. Press any key to begin."
};
/*define instructions block*/
var instructions_block = {
type:"text",
text:"<p>In this experiment,a circle will appear in the center" +
"of the screen.</p><p>If the circle is <strong>blue</strong>," +
"press the letter F on the keyboard as fast as you can.</p>" +
"<p>If the circle is <strong>orange</strong>, do not press " +
"any key.</p>"+
"<div class ='left center-conten'><img src='img/blue.png'></img>" +
"<p class = 'small'><strong>Press the F key</strong></p></div>" +
"div class='right center-content'><img src='img/orang.png'></img>" +
"<p class='small'><strong>Do not press a key</strong></p></div>" +
"<p>Press any key to begin.</p>", //<-- YOU NEED A COMMA HERE
timing_post_trial: 2000
};
EDIT: Another typo (math.random() should be Math.random());
var post_trial_gap = function() {
return Math.floor( Math.random() * 1500) + 750;
}
Here is the updated code:
/* define welcome message block */
var welcome_block = {
type: "text",
text: "Welcome to the experiment. Press any key to begin."
};
/* define instructions block */
var instructions_block = {
type: "text",
text: "<p>In this experiment, a circle will appear in the center " +
"of the screen.</p><p>If the circle is <strong>blue</strong>, " +
"press the letter F on the keyboard as fast as you can.</p>" +
"<p>If the circle is <strong>orange</strong>, do not press " +
"any key.</p>" +
"<div class='left center-content'><img src='img/blue.png'></img>" +
"<p class='small'><strong>Press the F key</strong></p></div>" +
"<div class='right center-content'><img src='img/orange.png'></img>" +
"<p class='small'><strong>Do not press a key</strong></p></div>" +
"<p>Press any key to begin.</p>",
timing_post_trial: 2000
};
/* define test block */
var test_stimuli = [
{
stimulus: "img/blue.png",
data: { response: 'go' }
},
{
stimulus: "img/orange.png",
data: { response: 'no-go' }
}
];
var all_trials = jsPsych.randomization.repeat(test_stimuli, 10);
var post_trial_gap = function() {
return Math.floor( Math.random() * 1500 ) + 750;
}
var test_block = {
type: "single-stim",
choices: ['F'],
timing_response: 1500,
timing_post_trial: post_trial_gap,
on_finish: function(data){
var correct = false;
if(data.response == 'go' && data.rt > -1){
correct = true;
} else if(data.response == 'no-go' && data.rt == -1){
correct = true;
}
jsPsych.data.addDataToLastTrial({correct: correct});
},
timeline: all_trials
};
/* define debrief block */
function getSubjectData() {
var trials = jsPsych.data.getTrialsOfType('single-stim');
var sum_rt = 0;
var correct_trial_count = 0;
var correct_rt_count = 0;
for (var i = 0; i < trials.length; i++) {
if (trials[i].correct == true) {
correct_trial_count++;
if(trials[i].rt > -1){
sum_rt += trials[i].rt;
correct_rt_count++;
}
}
}
return {
rt: Math.floor(sum_rt / correct_rt_count),
accuracy: Math.floor(correct_trial_count / trials.length * 100)
}
}
var debrief_block = {
type: "text",
text: function() {
var subject_data = getSubjectData();
return "<p>You responded correctly on "+subject_data.accuracy+"% of "+
"the trials.</p><p>Your average response time was <strong>" +
subject_data.rt + "ms</strong>. Press any key to complete the "+
"experiment. Thank you!</p>";
}
};
/* create experiment timeline array */
var timeline = [];
timeline.push(welcome_block);
timeline.push(instructions_block);
timeline.push(test_block);
timeline.push(debrief_block);
/* start the experiment */
jsPsych.init({
timeline: timeline,
on_finish: function() {
jsPsych.data.displayData();
}
});
After fetching the library and creating a blue and orange png I ran the experiment with the following correction to your last code post. The plugin name you have is incorrect. By the way, my time was 303ms.
<script src="jspsych-5.0.3/plugins/jspsych-single-stim.js"></script>

highlightSeries plugin for jquery flot charts

I'm looking for help with the highlightSeries plugin made by Brian Peiris (http://brian.peiris.name/highlightSeries/). It doesn't appear to be working; I'm positive that the event is firing, because an alert test I performed earlier worked just fine, printing out $(this).text(). I'm trying to get the series on the chart to be highlighted when the user mouses over the series name in the legend (something which works perfectly fine on Mr. Peiris's website).
$('.server-chart').each(function() {
var serv = $(this).attr('id').substr(6);
var plotData = [];
//alert(serv + ": " + $.toJSON(serverStats[serv]));
for (var k in serverStats[serv].StatsByCollection) {
var outlabel = k;
var outdata = serverStats[serv].StatsByCollection[k];
plotData.push({ label: outlabel, data: outdata});
}
plotOptions = {
legend: {
container: $('#legend-' + serv),
labelFormatter: function(label, series) {
return '' + label + '';
},
noColumns: 2
},
series: {
lines: {
show: true,
fill: false
},
points: {
show: false,
fill: false
}
},
colors: colors,
grid: {
hoverable: false
},
highlightSeries: {
color: "#FF00FF"
}
}
$_plot = $.plot(this, plotData, plotOptions);
$plots.push($_plot);
$('#legend-' + serv + ' .legendLabel, #legend-' + serv + ' .legendColorBox').on('mouseenter', function () {
$_plot.highlightSeries($(this).text());
});
$('#legend-' + serv + ' .legendLabel, #legend-' + serv + ' .legendColorBox').on('mouseleave', function () {
$_plot.unHighlightSeries($(this).text());
});
});
I'm not sure what other code to put on here, so tell me if you need more; the charts are all working fine, this is just the part of the ready function setting up all of the plots and their options inside the placeholders.
Also, there's a couple of classes attached to the labels that are extraneous; I was trying different things to get this stuff to work.
The plugin requires a patched version of flot to work (it introduces a public drawSeries method). The last patched version is for an older version of flot (0.7).
With that said, I wouldn't use this plugin. If you just want to highlight a series on legend mouseover it's pretty simple.
$('#legend .legendLabel, #legend .legendColorBox').on('mouseenter', function() {
var label = $(this).text();
var allSeries = $_plot.getData();
// find your series by label
for (var i = 0; i < allSeries.length; i++){
if (allSeries[i].label == label){
allSeries[i].oldColor = allSeries[i].color;
allSeries[i].color = 'black'; // highlight it in some color
break;
}
}
$_plot.draw(); // draw it
});
$('#legend .legendLabel, #legend .legendColorBox').on('mouseleave', function() {
var label = $(this).text();
var allSeries = $_plot.getData();
for (var i = 0; i < allSeries.length; i++){
if (allSeries[i].label == label){
allSeries[i].color = allSeries[i].oldColor;
break;
}
}
$_plot.draw();
});
See example here.

how to load data while scrolling in div?

Today I saw my Facebook account and scroll the contend bottom. After some time I found it load more -2 data while scrolling (scroll position same where it was previously). I think it is new functionality given by Facebook. Previously they first go to bottom and get that event than load the data example pull to refresh. Can we do load new data while scrolling so that it look all data in same page ?
http://jsfiddle.net/N5LZB/28/
$(document).ready(function(){
$('#fullContainer').on('scroll', function () {
if ($(this).scrollTop() === 0 ) {
// alert('--')
if(file_show_counter>0){
var precontent=$("#preRealTimeContents").html();
//$("#loadingImg").hide();
$("#realTimeContents").html($("#preRealTimeContents").html() + '<div style="clear:both;"></div>');
console.log("preRealTimeContents : " + $("#preRealTimeContents").height());
//$("#preRealTimeContents").html('');
$("#preRealTimeContents").html(pages[--file_show_counter]+ '<div style="clear:both;"></div>');
$("#fullContainer").scrollTop(
$("#preRealTimeContents").height()
);
}
}
else if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight ) { if(++file_show_counter<count) {
//alert(file_show_counter);
$("#preRealTimeContents").html($("#realTimeContents").html());
$("#realTimeContents").html(pages[file_show_counter+1]+'<div style="clear:both;"></div>');
$("#fullContainer").scrollTop(
$("#preRealTimeContents").height()- $("#fullContainer").height()
);
}else {
file_show_counter--;
}
}
});
});
Thanks
Try this (pattern)
css
#realTimeContents div {
padding-top : 8px;
padding-bottom : 8px;
}
js (updated)
$(function () {
var page_0 = "Shikhar Dhawan is an Indian international cricketer."; // `page_1`
var page_1 = "Rohit Gurunath Sharma is an Indian international cricketer."; // `page_2`
var page_2 = "Virat Kohli is an Indian cricketer."; // `page_3`
var page_3 = "Suresh Raina is currently a player of Indian Cricket Team"; // `page_4`
var page_4 = "Yuvraj Singh is an Indian international cricketer."; // `page_5`
var pages = [page_0, page_1, page_2, page_3, page_4];
$("#fullContainer")
.find("#preRealTimeContents")
.html("<div id=0>" + pages[0] + "</div>")
.parent("#fullContainer")
.one("scroll", function (e) {
$.each(pages.slice(1, 5), function (k, v) {
$("#realTimeContents")
.append("<div id=" + (++k) + ">" + v + "</div>");
// append `2` `pages`,
// adjust for number
// of `pages` to append
// i.e.g., `0` - `4`
return (k != 2)
});
});
});
jsfiddle http://jsfiddle.net/guest271314/h95h5/

Hide a column in flexigrid

Is there a way to hide and show a column in jQuery flexigrid like this?
$('#FlexigridID').hideCol('ColumnName');
$('#FlexigridID').showCol('ColumnName');
New code tested:
$(function () {
var visible = true;
$('#yo').click(function () {
alert('hello');
visible = !visible;
showColumn('#yourFlexigridNameHere', 'Lastname', visible);
});
});
// you can put this in a separate javascript library
function showColumn(tbl, columnName, visible) {
var grd = $(tbl).closest('.flexigrid');
var colHeader = $('th[abbr=' + columnName + ']', grd);
var colIndex = $(colHeader).attr('axis').replace(/col/, "");
// queryVisible = $(colHeader).is(':visible');
// alert(queryVisible);
$(colHeader).toggle(visible);
$('tbody tr', grd).each(
function () {
$('td:eq(' + colIndex + ')', this).toggle(visible);
}
);
}
HTML:
<input id='yo' type="button" />
You can also set the hide to false on flexigrid's colModel setup:
colModel: [
{display: 'Row ID', name : 'Lastname', width : 100,
sortable : true, align: 'left', hide: false}
You can also add a method against flexigrid, you can put this in a separate javascript library:
(function ($) {
$.fn.showColumn = function (columnName, visible) {
if (visible == undefined) visible = true;
var grd = this.closest('.flexigrid');
var colHeader = $('th[abbr=' + columnName + ']', grd);
var colIndex = $(colHeader).attr('axis').replace(/col/, "");
$(colHeader).toggle(visible);
$('tbody tr', grd).each(
function () {
$('td:eq(' + colIndex + ')', this).toggle(visible);
}
);
};
$.fn.hideColumn = function (columnName) {
this.showColumn(columnName, false);
}
})(jQuery);
You can now invoke hiding and showing using these:
$('#FlexigridID').hideColumn('ColumnName');
$('#FlexigridID').showColumn('ColumnName');
visible = !visible; // for toggling need
$('#FlexigridID').showColumn('ColumnName', visible);
Try this:
$('#FlexigridID').find("tr td").eq(columnIndex).hide();
$('#FlexigridID').find("tr td").eq(columnIndex).show();
Try something like this
$('td:nth-child(2)').hide();
for table with header(th)
$('td:nth-child(2),th:nth-child(2)').hide();
Read more about Hide a Table Column with a Single line of jQuery code
$("#yourFlexigridNameHere").flexToggleCol(columnIndex, false);
//columnIndex - starts from 0

Categories

Resources