JQuery .load () in a loop does not work - javascript

Trying to run the following code, but it works either way I need to:
if(my_condition){
$('body').append("<div id='loaddiv'><div>");
for(var i=1; i<=100; i++){
var dl = 0;
$('#loaddiv').load('/script/?p='+i);
dl = $('#loaddiv .standart-view tr').length;
alert(dl);
}
}
Thus, I have to get the number of tr-elements, which is the parent element with class standart-view, and his parents - div block c id = load214235, for each page, but constantly displays zeros in the Alert :( I tried to upgrade the code, adding all the code in the load-callback function, but still does not work ...
if(my_condition){
$('body').append("<div id='loaddiv'><div>");
for(var i=1; i<=100; i++){
var dl = 0;
$('#loaddiv').load('/folder/?p='+i, function(){
dl = $('#loaddiv .standart-view tr').length;
alert(dl);
});
}
}
+I have yet to load after going condition with break; firebug it just swears that break does not know that close ... How do I get out of the situation? I feel that something with a visibility of variables and data do not have time to load another page, and the script is running on. Jquery is connected, the rest of the code is working, including the functions of jquery, the hierarchy of elements on another page observed (number of tr should be).

First load is an Asynchronous call, you are treating it as synchronous. You are reading the content before the Ajax call is returned. Hence why it is always zero.
Second, when you do hook it up write, the content will end up writing on top of each other. You can not use load() and expect it to work in a loop.
Here is the basic idea:
(function () {
var pageCounter = 1;
var tableRowsTotal = 0;
max pageMax=10;
function loadPage() {
$.get('/folder/?p='+pageCounter, function(data){
var table = $(data).filter(".standart-view");
//or
//var table = $(data).find(".standart-view");
var rows = table.find("tbody tr");
var rowCount = rows.length;
console.log(pageCounter, rowCount);
tableRowsTotal += rowCount;
pageCounter++;
if(pageCounter<pageMax) {
loadPage();
} else {
console.log("done");
}
});
}
loadPage();
}());

Related

`How to change between list view and grid view and also keep the current state after page refresh

I need to toggle between list view and grid view which i was able to do using js to change the css but the problem is if a user refresh the page the default view is restored, how can I make this, probably append the view name to the url so that the current view will remain after user refresh page. example having the following URl www.example.com/item/search?q=myquery&style=list, www.example.com/item/search?q=myquery&style=grid, or is there a better way to do this. below is a fiddle of my code and any refresh will return the view to grid even when i select list view
JS FIDDLE
Note: I'm using yii2 framework so regarding the url formation i'm open to both php and JS solution, thanks in advance
$(".listView").on('click', function() {
listView();
});
$(".gridView").on('click', function() {
gridView();
});
// Get the elements with class="column"
var elements = document.getElementsByClassName("column");
// Declare a loop variable
var i;
// List View
function listView() {
for (i = 0; i < elements.length; i++) {
elements[i].style.width = "100%";
}
}
// Grid View
function gridView() {
for (i = 0; i < elements.length; i++) {
elements[i].style.width = "50%";
}
}
var container = document.getElementById("btnContainer");
var btns = container.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
btns[i].addEventListener("click", function() {
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className += " active";
});
}
In order to do what you want, actually you dun need to do any work on backend but simply using the cookie.
You may improve it, I just provide a picture.
$(".listView").on('click', function() {
listView();
setCookie('list');
});
$(".gridView").on('click', function() {
gridView();
setCookie('grid');
});
function setCookie(name) {
document.cookie = name;
}
And when you start the JS, check the cookie first by
var x = document.cookie;
if (x == 'list'){...}
else if (x == 'grid'){...}
You may also choose to use localStorage, the technical is the same. However, only when if you list and grid data has no difference, and no server data is further required.
I think MatrixTai has the right idea, but I personally prefer usually localStorage.
Here is an example with a functions for getting/setting the view:
$(".listView").on('click', function() {
listView();
setView('list');
});
$(".gridView").on('click', function() {
gridView();
setView('grid');
});
function setView(view) {
localStorage.setItem('view', view);
}
function getView(view) {
return localStorage.getItem('view');
}

How to populate jqGrid filter toolbar and search when the page loads (ASP.net webforms)

Currently, I'm trying to populate the filterToolbar with values taken in from a cookie. If there is cookie data for the filters, I want it to fill the respective textboxes and filter the jqGrid for that data.
I'm using ASP.net webforms, so most of my data is initialized already. How/where could I add javascript in order to get this going?
I actually figured out what I was doing.
So what I ended up doing as a solution was adding a timeout function in the document.ready function
$(document).ready(function () {
// some code
setTimeout(function () {
$('#Jqgrid1')[0].triggerToolbar();
}, 500)
//some code
}
My guess is that I couldn't use the $('#grid')[0].toggleToolbar() to force it because whenever I tried to use it, it was before the whole grid was finish setting up.
In the ASP webform, I had several functions registered.
<cc1:JQGrid ID="Jqgrid1" runat="server"
Height="630"
SearchDialogSettings-Draggable="true"
EnableViewState="false"
AutoWidth="True" >
<ClientSideEvents
LoadComplete="Jqgrid1_LoadComplete"
GridInitialized="initGrid"
/>
<%-- grid code --%>
</cc1:JQGrid>
The LoadComplete is executed after the grid is loaded. I tried doing triggering my toolbar there, but didn't work. My guess is, again, it was too early in the grid execution to use the triggerToolbar() function.
The same went for the GridInitialized events (even though both events would seem to imply to me that the grid is done doing its thing... but whatever...)
The way that I read my cookies in was actually in the GridInitialized event handler.
function initGrid() {
var myJqGrid = $(this);
var valueName = 'GridFilters';
var myCookie = document.cookie;
var gridFilterString;
var gridFilterArray;
var currentFilter;
var myCookie_arr;
var myDic = {};
if (myCookie.indexOf(valueName) > -1) { // don't even bother if the cookie isn't there...
myCookie_arr = myCookie.split("; "); // looking for the cookie I need
// read cookies into an array
for (var i = 0; i < myCookie_arr.length; i++)
{
parts = myCookie_arr[i].split("=");
first = parts.shift(); // remove cookie name
myDic[first.trim()] = parts.join("=").trim(); // handles multiple equality expressions in one cookie
}
if (myDic.hasOwnProperty("GridFilters"))
gridFilterString = myDic["GridFilters"];
if (gridFilterString != "NONE") {
myFiltersDic = {}
myFiltersArr = gridFilterString.split("&")
for (var i = 0; i < myFiltersArr.length; i++) {
parts = myFiltersArr[i].split("=");
myFiltersDic[parts[0].trim()] = parts[1].trim();
}
myParams = $(this).jqGrid("getGridParam", "postData");
var filters = []
for (keys in myFiltersDic) {
$('#gs_' + keys.trim()).val(myFiltersDic[keys].trim());
}
$.cookie('m_blnSearchIsHidden', "0", "/");
if (!isLoaded)
{
$(this)[0].toggleToolbar();
}
isLoaded = true;
}
}
}

Reload a content almost invisibly and no blinking effect using JAVASCRIPT

I'm writing a small progam wherein I'm getting data using $.get then display the data so far so good and then there's this part then when I click a certain link it refresh the page but it has this blinking effect. Is there a way on how to reload the content get the new updated content then replace the previously loaded data.
NOTE: I didn't use setInterval or setTimeout function because it slows down the process of my website. any answer that does not include those functions are really appreciated.
Here's the code
function EmployeeIssues(){
$('#initial_left').css({'display' : 'none'});
var table = $('#table_er');
$.get('admin/emp_with_issues', function(result){
var record = $.parseJSON(result);
var data = record.data,
employees = data.employees,
pages = data.pages;
if(employees){
$('#er_tab_label').html('<b>Employees with Issues</b>');
for (var i = 0; i < employees.length; i++) {
$('#table_er').fadeIn('slow');
table.append(write_link(employees[i])); // function that displays the data
}
if(pages){
$('#pagination').html(pages);
}
}else{
$('#er_tab_label').html('<b>No employees with issues yet.</b>');
}
});
table.html('');
}
then this part calls the function and display another updated content
$('#refresh_btn').on('click', function(e){
e.preventDefault();
var tab = $('#tab').val();
if(tab == 'er'){
EmployeeIssues();
}
});
What should I do to display the content without any blinking effect?
thanks :-)
This section might be the issue :
if(employees){
$('#er_tab_label').html('<b>Employees with Issues</b>');
for (var i = 0; i < employees.length; i++) {
$('#table_er').fadeIn('slow');
table.append(write_link(employees[i])); // function that displays the data
}
if(pages){
$('#pagination').html(pages);
}
} else ...
It seems you're asking table_er to fade in once per run of the loop whereas s there can only be one such table, you only need to do it once ?
first try re-arringing it like this:
if(employees){
$('#er_tab_label').html('<b>Employees with Issues</b>');
$('#table_er').hide(); // hide it while we add the html
for (var i = 0; i < employees.length; i++) {
table.append(write_link(employees[i])); // function that displays the data
}
$('#table_er').fadeIn('slow'); // only do this after the table has all its html
if(pages){
$('#pagination').html(pages);
}
} else ....
Another possibility is that you're running through a loop and asking jquery to do stuff while the loop is running. It might be better to work out the whole HTML for the new page data in a string and then get the screen to render it in one line. I cna't do this for you as I don't know what's in write_link etc but something like this ..
if(employees){
$('#er_tab_label').html('<b>Employees with Issues</b>');
var sHTML ="";
$('#table_er').hide(); // hide it while we add the html
for (var i = 0; i < employees.length; i++) {
sHTML+=write_link(employees[i]); // maybe this is right ? if write_link returns an HTML string ?
}
table.append(sHTML); // add the HTML from the string in one go - stops the page rendering while the code is running
$('#table_er').fadeIn('slow'); // now show the table.
if(pages){
$('#pagination').html(pages);
}
} else ...

Accessing a specific control located in the footer template of a column using client side

I need to access a label (lblTotalWeight) that is located in the footer template of a gridtemplatecolumn. From there I want to change the forecolor, though I want to do this all clientside. You can see in my function below that I have already accessed each row successfully, though it seems that doing so for the footer is not as straight forward. My research thus far keeps leading to server side solutions, or in once case a hardcoded row[] cell[] situation.
get_masterTableViewFooter has yet to return anything.
Oh my code behind is in C#.
JavaScript:
function GridCreated(sender, eventArgs) {
grid = $find("<%=rgActivities.ClientID %>");
var masterTable = grid.get_masterTableView();
var rows = masterTable.get_dataItems();
var total = 0.0;
for (var row = 0; row < rows.length; row++) {
var rcb = rows[row].findControl("rcbWeight");
total += parseInt(rcb.get_value());
}
if (total== 100) {
//lblTotalWeight = black;
}
else {
//lblTotalWeight = Red;
}
}
(As a sidenote rcb is RadComboBox.)
Thanks!
You might need to tweak it a bit, but something like this should get you close:
var footerLabelID = '<%= ((GridFooterItem)rgActivities.MasterTableView.GetItems(GridItemType.Footer)[0]).FindControl("lblTotalWeight").ClientID %>';
var footerLabel = document.getElementById(footerLabelID);
if (footerLabel){
footerLabel.innerText = "Hello World!";
}

Elements By ClassName Failing

I am creating sliding menus in JavaScript, and the following is my init() function:
function init() {
var menus = new Array();
var allElems = document.getElementsByTagName("*");
for (var i = 0; i < allElems.length; i++) {
alert(allElems[i]);
if (allElems[i].className == "navG") {
alert(allElems[i]);
menus.push(allElems[i]);
}
}
/* assign the openMenu function to the onclick event for each
Menus item */
for (var i = 0; i < menus.length; i++) {
alert(menus[i]);
menus[i].onclick=openMenu;
}
document.getElementById("logo").onclick = closeMenu;
document.getElementById("linkList").onclick = closeMenu;
document.getElementById("main").onclick = closeMenu;
}
The problem seems to be in the first for loop. This is definitely the correct class name..just for reference, this is the type of HTML that I am referring to:
<div class="navG" id="gallery1" style="position: absolute; top: 180px; left: -150px; " >
Is there an obvious, or not so obvious reason, that this is not adding the elements to menus?
You got a bug here
document.getElementById("logo").onclick = closeMenu();
document.getElementById("linkList").onclick = closeMenu();
document.getElementById("main").onclick = closeMenu();
You calling closeMenu, not assigning it.
Needs to be
document.getElementById("logo").onclick = closeMenu;
document.getElementById("linkList").onclick = closeMenu;
document.getElementById("main").onclick = closeMenu;
In the page you linked to, in your family.js script, this line:
window.onLoad = init();
says to run the init function immediately and assign its return value to window.onLoad. Because it is running immediately the actual document hasn't been parsed yet so it doesn't find any of your elements. You need to say this:
window.onload = init;
which assigns a reference to the init function to window.onload so that that function will be run later after all of the elements have been parsed.
Also onload should have a lowercase l.
(There are some other problems in your code, e.g., you don't seem to have elements with the ids "linkList" or "main", but I think what I said above is the main problem with the part you are asking about.)
Whoops, you're missing quotes around that "navG" in the first loop.

Categories

Resources