Javascript - Load one time - javascript

I have Javascript loading some data and because its in a loop it ends up loading multiple times which causes lengthy wait times. I need to find how to load it only once. I researched the issue and found some code but not sure how to implement it. Here is the best link I could find about my issue:
http://blog.michaelckennedy.net/2012/10/11/preventing-javascript-files-from-loading-multiple-times/
Update: Sorry it took so long to get back. I just work Wednesday through Saturday. I was asked to give my entire code. I trimmed it down considerably.
Script I'm Loading to pull only once
jQuery(function($)
{
$('#resultA').load('DocText.html #Tablemain1');
$('#resultB').load('DocText.html #Tablemain2');
Entire Code
table class="tblrohs6" border="5" cellpadding="3" cellspacing="2">
<tr>
<td align="center">
<script type="text/javascript">
var title = document.getElementsByTagName( "title" ).item(0);
document.write('<iframe src="http://some.company.com/mfgsupt/testeng/eac/b4home/city/abistatus.asp?Bldg=City&abiID='+title.innerHTML+'&Training=no" id="abiIframe" Name="abiIframe" width="550" height="55" marginwidth="0" marginheight="0" hspace="0" vspace="0" frameborder="0" ></iframe>');
</script>
<SCRIPT SRC="file://///namp-dsk-003/cim-cam/CAM/BOI/Abi/680/Common_Files/TitleCheck.js"></SCRIPT>
</td>
</tr>
<tr>
<td bgcolor="#FFFFFF">
<!----------------StartMain Table Placement-------------------------->
<p class="revisionmain"> Text List - Assembly Build Instructions</p>
<script>
$('#resultA').load('DocText.html #Tablemain1');
$('#resultB').load('DocText.html #Tablemain2');
</script>
<p id="resultA"></p>
<!---------------Start Assembly Buttons------------------------------->
<table width="80%" border="1" align="center">
<tr>
<td colspan="10"><div align="center" class="row-column-headers-RoHS">Assembly Selection</div></td>
</tr>
<tr>
<td><div align="center"><button id="b1" onclick="showX(2)"> 178-0416-00 </button></div></td>
<td><div align="center"><button id="b2" onclick="showX(3)"> 178-0427-00 </button></div></td>
</tr>
<tr>
<td colspan="9">
<div align="center"><button onclick="location.reload();"> Refresh </button></div>
</td>
</tr>
</table>
<!-------------------End Assembly Button------------------------------->
<p id="resultB"></p>
<p id="resultC"></p>
</td>
</tr>
<!--------------------End Main Table Placement--------------------------->
<tr>
<td class="bodycell"><p class="section">Lower Level Casing </p>
<table style="visibility:visible" width="100%" border="2">
<tr>
<td colspan="3"><ol start="1">
<!----------------------------------Body After Tables------------------------------------------------>
<p id="result1"></p>
<p id="result2"></p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
<!-------------------------------------- END Body After Tables------------------------------------------>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<!--------------- Start Column Selector for button--------Input at end of this doc----------->
<script>
function showX(num) {;
<!--------------- Start Column Selector for button--------Input at end of this doc----------->
<!--------------------- Start Search Column for None------------------------>
var tab = document.getElementById('part1Table');
var l = tab.rows.length;
for ( var i = 0; i < l; i++ ) {
var tr = tab.rows[i];
var cll = tr.cells[num];
if(s = cll.innerText.indexOf('None') != -1)
{
<!---------------------- End Search Column for None------------------------->
<!---------------- Start Place Lines in Document--------------------->
jQuery(function($)
{
$('#resultA').load('DocText.html #Tablemain1');
$('#resultB').load('DocText.html #Tablemain2');
if (num==2) {
$('#resultE').load('DocText.html #0416');}
if (num==3) {
$('#resultF').load('DocText.html #0427');}
$('#result1').load('DocText.html #Line1');
$('#result2').load('DocText.html #Line2');
});
<!------------------ End Place Lines in Document----------------------->
if (i==1) /*Change this for "Line in ABI Doc" */
{ var e = document.getElementById('result1'); /*Change this for "Line Hidden" */
e.style.display = 'none';}
if (i==2) /*Change this for "Line in ABI Doc" */
{ var e = document.getElementById('result2'); /*Change this for "Line Hidden" */
e.style.display = 'none';}
}}} </script>
<!-------------------------------------Start Pull part1Table Data ---------------------------------------->
<script type="text/javascript">
jQuery(function($)
{
$('#resultZZ').load('DataTableUpdate3.html #part1Table');
});
</script>
<p id="resultZZ"></p>
<!--This is for Button Column Selector, Very Important -->
<input type="text" id="cellnum" value="0"/>
<!--This is for Button Column Selector, Very Important -->

Just to let you know, your showX(num) function on line 73 of your given code, you have a broken function that isn't going to run.
function showX(num) {;

You could set a variable and check if it is set.
Example:
if (!window.dataIsLoaded) {
// load the data
}
window.dataIsLoaded = true;
But of course it would be much better to avoid executing this part of the code in some loop. You should provide more context to understand what you're doing and why the data would be loaded in a loop.

I ended up looking closer to the code and was able to take my .loads out of the loop. Now as a result it is no longer reloading the same objects multiple times. Thank for all the input. I guess sometimes re-organizing makes all the difference.

Related

How to Add Table Filter with JS?

I've been trying to add a search filter to a table using JavaScript, I've downloaded jQuery on my computer as well as for browser but the search filter still won't work.
var $rows = $('#table tr');
$('#search').keyup(function() {
var val = $.trim($(this).val()).replace(/ +/g, '' ).toLowerCase();
$rows.show().filter(function() {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header id="top">
<!--id "top" for a "return to top of page" button-->
<h1>
<!--header-->
CryptoCost<img width="25">
<font size="4"><span class="Priceandmarketcap">Live Cryptocurrency Prices & Market Capitalization</span></font>
<font size="2"><span class="SearchCoinsHead">Search Coins:
<font><input type="text" id="search" class="light-table-filter" placeholder="BTC.."></font></span></font>
</h1>
</header>
<br>
<!--vertical whitespace-->
<span class="indextable">
<table id="table">
<tr>
<th>#</th> <!--table headers-->
<th>Coins</th>
<th>Price</th>
<th>24H Change</th>
<th>24H Volume</th>
<th>Market Cap</th>
<th>Circulating Coin Supply</th>
</tr>
<tr> <!--start of new row-->
<td>1</td> <!--coin number-->
<td> <img src="" width="15"> BTC </td>
<!--icon & ticker-->
<td><big>$7000</big></td> <!--price-->
<td><big>-15%</big></td> <!--24H % Change-->
<td><big>30,284 BTC</big></td> <!--24H Volume-->
<td><big>$117,727,059,656</big></td> <!--Market Cap-->
<td><big>16,946,875 BTC</big></td> <!--Circulating Coin Supply-->
</tr>
<tr>
<td>2</td>
<td> ETH </td>
<td><big>$400</big></td>
<td><big>+32%</big></td>
<td><big>98,497,625 ETH</big></td>
<td><big>$37,143,553,062</big></td>
<td><big>98,497,625 ETH</big></td>
</tr>
<tr>
<td>3</td>
<td> <img src="" width="15"> LTC </td>
<td><big>$120</big></td>
<td><big>-40%</big></td>
<td><big>55,849,820 LTC</big></td>
<td><big>$6,269,309,798</big></td>
<td><big>55,849,820 LTC</big></td>
</tr>
</table>
</span>
This is one of those situations where you really should just go ahead and choose a library. Reason being is you are most likely going to want to add additional features (like your filtering) and "reinventing the wheel" isn't the best approach in many cases.
I would highly suggest a free and open-source library called, DataTables. It will provide an incredible amount of features (including filtering) and will also provide you with a fully responsive table implementation - which is critical nowadays. In addition, it is based off of jQuery - which you are already using:
https://datatables.net/
If you are just playing around then please ignore this answer - but if you're creating a real website that will be published I'd suggest using a library.
You're not including your script correctly.
This:
<script>
src="http://code.jquery.com/jquery-
3.3.1.min.js"integrity="sha256-
FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="crossorigin="anonymous">
</script>
Should be:
<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8" crossorigin="anonymous">

Print something from JavaScript to a table in HTML/PHP page

I want to print out the result of a JavaScript function to a table in my HTML/PHP page. I tried using " document.write(player1Name);"
but it didn't work.
So when i input something into this text field
I want that result to be printed in this table
This is the code in my Hangman Home Page :
<form id="Player1" class="Player1">
<input type="text" id="playerOneName"/>
</form>
<form id="Player2" class="Player2">
<input type="text" id="playerTwoName"/>
</form>
<button id="Enter" class="Enter" type="button" onclick="navigateToDifficultyForMultiPlayer()">
<a>Enter</a>
</button>
This is the code in my Multi-player page for the table:
<TABLE BORDER="5" WIDTH="20%" CELLPADDING="5" CELLSPACING="2" id="Score-Board">
<TR>
<caption id="table-title">Score Board</caption>
</TH>
</TR>
<TR ALIGN="CENTER">
<TH colspan="2"> <script> document.write(player1Name);</script> </TH>
<TH colspan="2"><script> var player2Name </script></TH>
</TR>
<TR ALIGN="CENTER">
<TH colspan="2">score</TH>
<TH colspan="2">score</TH>
</TR>
</TABLE>
This is my JavaScript code I created to do what I want it to do (I think I have done it right):
function navigateToDifficultyForMultiPlayer() {
//set player names in session
setPlayerNames();
//navigate to DifficultyForMultiPlayer page
location.href = "DifficultyForMultiPlayer.html";
}
function setPlayerNames() {
var firstPlayerName = document.getElementById("playerOneName").value;
var secondPlayerName = document.getElementById("playerTwoName").value;
console.log(firstPlayerName + " " + secondPlayerName);
sessionStorage.setItem("Player1Name", firstPlayerName);
sessionStorage.setItem("Player2Name", secondPlayerName);
}
function getPlayerNames(){
player1Name = sessionStorage.getItem("Player1Name");
player2Name = sessionStorage.getItem("Player2Name");
console.log(player1Name + " " + player2Name);
}
And this is the JavaScript that's being called globally :
var player1Name;
var player2Name;
I hope everyone can understand what I am trying to ask. Please don't hesitate to tell me if there is something wrong with my question. I tried my best to ask the question properly, FYI English isn't my first language
What you want to do is in this html:
<TR ALIGN="CENTER">
<TH colspan="2"> <script> document.write(player1Name);</script> </TH>
<TH colspan="2"><script> var player2Name </script></TH>
</TR>
add an ID to your th elements:
<TH colspan="2" id="player1"> // and remove the script
Then, in your javascript, possibly in your getPlayerNames function:
document.getElementById("player1").text(player1Name);
And then do the same for player2.
You can give your <th> tags for the players ids like player1 and player2. Then at the end of your <body> for the Multi-player page you can put a <script> tag that does something like:
<script>
(function() {
document.getElementById("player1").innerHTML = player1Name;
document.getElementById("player2").innerHTML = player2Name;
})();
</script>
The document.getElementById grabs the DOM element that you want and then .innerHTML changes what is within that tag. Putting this right before end of the body tag will make sure the html elements are loaded first before trying to access them.

IBM Worklight - How to re-use a function in a multipage app

I have used the function doTimer() on the page level-one-1, and now I'm trying to reuse the function doTimer() on the second page. But it doesn't work. Can anyone help me?
Here is my javascript and html code.
The JS:
var start = new Date().getTime();
var elapsed = '0.0';
var t;
var timer_is_on=0;
function timedCount() {
var time = new Date().getTime() - start;
elapsed = Math.floor(time / 100) / 10;
if(Math.round(elapsed) == elapsed) { elapsed += '.0'; }
document.getElementById('txt').value=elapsed;
t=setTimeout("timedCount()",50);
}
function doTimer() {
if (!timer_is_on) {
start = new Date().getTime();
timer_is_on=1;
timedCount();
}
}
function stopCount() {
clearTimeout(t);
timer_is_on=0;
}
function resetCount() {
document.getElementById('txt').value='0.0';
var elapsed = '0.0';
}
The HTML:
<!-- Page Level 1-1 start -->
<div id="level-one-1" data-role="page" >
<div data-role="header">
<h1>StarKids</h1>
</div>
<div data-role="content">
<table>
<tr>
<td id="level-1">Level 1</td>
<td colspan="3" id="center-top"></td>
<td id="txt">
</td>
</tr>
<tr>
<td id="settings">Setting</td>
<td colspan="3" id="center-top">Which animal is monkey?</td>
<td id="overallscore"></td>
</tr>
<tr>
<td colspan="2"><a onclick="checkAnswer1a()"><img id="tortoise" src="images/duck.png" ></a></td>
<td><img id="elephant" src="images/duck.png" onclick="checkAnswer1a()"></td>
<td colspan="2"><img id="giraffe" src="images/duck.png" onclick="checkAnswer1a()"></td>
</tr>
<tr>
<td colspan="2"><img id="monkey" src="images/duck.png" onclick="checkAnswer1a()"></td>
<td></td>
<td colspan="2"><img id="owl" src="images/duck.png" onclick="checkAnswer1a()"></td>
</tr>
<tr>
<td colspan="5" id="next">Next</td>
</tr>
</table>
</div>
<div data-role="footer">
<!-- Copyright © anitaagustina 2013 -->
</div>
</div>
<!-- Page Level 1-1 end -->
<!-- Page Level 1-2 start -->
<div id="level-one-2" data-role="page" onload="doTimer()">
<div data-role="header">
<h1>StarKids</h1>
</div>
<div data-role="content" >
<table id="tabel-soal">
<tr>
<td id="level-1">Level 1</td>
<td colspan="3"> </td>
<td id="txt">
</td>
</tr>
<tr>
<td id="settings">Setting</td>
<td colspan="3">Match each word to its picture</td>
<td id="overallscore"></td>
</tr>
<tr>
<td> </td>
<td>image:elephant</td>
<td>image:elephant</td>
<td>image:elephant</td>
<td> </td>
</tr>
<tr>
<td> </td>
<td>empty-box</td>
<td>empty-box</td>
<td>empty-box</td>
<td> </td>
</tr>
<tr>
<td> </td>
<td>answer-choice-1</td>
<td>answer-choice-2</td>
<td>answer-choice-3</td>
<td> </td>
</tr>
<tr>
<td colspan="5">Next</td>
</tr>
</table>
</div>
<div data-role="footer">
<!-- Copyright © anitaagustina 2013 -->
</div>
</div>
<!-- Page Level 1-2 end -->
You do not mention in WHICH .js file you have placed this function nor how do you navigate between pages. This is crucial information. Add this information to your question.
In the context of a Worklight 6.1 application - without knowing anything else about your project - my suggestion is to place this function in the common\js\main.js file. This main.js file is referenced in the HEAD of your Worklight application's index.html file.
To reuse this function, you can then for example navigate between "pages" by replacing the contents of a DIV within the index.html file by using jQuery's load API method. This way the function is always available no matter which "page" you are loading.
These are two sample projects that implement "page" loading:
JQM_multipage_load_changePage.zip - uses either .load or .changePage
JQM_multipage_changePage_pageshow.zip - uses .changePage and .pageShow
Edit: using the provided demo project in the comments to this answer, I have changed the following in it:
Change this:
$(document).on("pageshow", "#one", function( event ) {
alert( "page 1 loaded" );
});
$(document).on("pageshow", "#two", function( event ) {
alert( "page 2 loaded" );
});
To this:
$(document).on("pageshow", "#one", function( event ) {
alert( "page 1 loaded" );
stopCount();
doTimer();
});
$(document).on("pageshow", "#two", function( event ) {
alert( "page 2 loaded" );
stopCount();
doTimer();
});
To verify doTimer() is indeed called, you can add an alert inside doTimer(), like alert ("in doTimer");
To verify stopCount() is indeed called, you can add an alert inside doTimer(), like alert ("in stopCount");
Remove the onload from the HTML:
From:
<div id="level-one-2" data-role="page" onload="doTimer()">
To:
<div id="level-one-2" data-role="page">
I finally come up with a solution.
Since I'm new to jquerymobile, I just knew that for multipage app, all of the pages are loaded via AJAX which is the problem why all of my function stop working when I navigated to other page. So before, I used mobile changepage to navigate, and now I changed them using href="#nextpage" and I added another attribute of data-rel="external". And now it's finally working.
my reference :
http://www.gajotres.net/how-jquery-mobile-page-handling-affects-javascript-executions/

Javascript table menu opens up with all tables already collapsed, why?

I have a simple menu with collapsing tables, working with Javascript. My problem is when I open it in the browser it comes up with all tables already collapsed! How can I open it with the menu sections "closed", to then collapse each section only onclick? I know it's in the Javascript but I'm new to it so bear with me... Thank you!
Here's the basic code:
<head>
<script>
function doCollapse(rowname)
{
theElement = document.getElementById(rowname);
if(theElement.style.display == 'none'){
theElement.style.display = '';
}else {
theElement.style.display = 'none';
}
return false;
}
</script>
</head>
<body>
<table>
<tr>
<td>
<p1 onClick=" doCollapse ('r1');">JQ</p>
</td></tr>
<tr>
<td id="r1">ver biografia</td></tr>
<tr>
<td>
<p2 onClick=" doCollapse ('r2');">Obras</p>
</td>
</tr>
<tr>
<td id="r2">lista</td></tr>
<tr>
<td>
<p3 onClick=" doCollapse ('r3');">Exposições</p>
</td>
</tr>
<tr>
<td id="r3">lista</td></tr>
</table>
</body>
</code>
Since you are using pure javascript and not a library like jquery, I'd suggest a couple of modification to easily target your elements. Try to put the items to show and hide inside a span so you can use document.getElementsByTagName and then add the Id to those spans rather than on td. My concern was that you have more td in your code, so you using document.getElementsByTagName would affect them as well, which is not what you need. However, you need to be careful that my solution would also suffer from that side effect if you have more spans in your code, which is likely, so you need to take this consideration before you implement this live. Here is the code and you can see a live demo here
<head>
<script>
function init(){
var numberOfRows = document.getElementsByTagName('span').length;
for (var i = 0; i < numberOfRows; i++){
document.getElementsByTagName('span')[i].style.display = 'none';
}
}
function doCollapse(rowname)
{
theElement = document.getElementById(rowname);
if(theElement.style.display == 'none'){
theElement.style.display = 'inline';
}else {
theElement.style.display = 'none';
}
return false;
}
</script>
</head>
<body onload="init()">
<table>
<tr>
<td>
<p onClick=" doCollapse ('r1');">JQ</p>
</td></tr>
<tr>
<td><span id="r1">ver biografia</span></td></tr>
<tr>
<td>
<p onClick=" doCollapse ('r2');">Obras</p>
</td>
</tr>
<tr>
<td><span id="r2">lista</span></td></tr>
<tr>
<td>
<p onClick=" doCollapse ('r3');">Exposições</p>
</td>
</tr>
<tr>
<td><span id="r3">lista</span></td></tr>
</table>

How to change the link in an active button dependent upon a variable

My web page is divided into day reports. As many as 25 per page. I have created a js array where I enter the titles for each day. For each day, a script runs that displays the appropriate title for that day.
Each day also has a button that a person can click and link to a google map for that day.
The button is formed by the following js and XXX is the link:-
document.write('<table id="vista-buttons_com_idkli11" width="0" cellpadding="0"
cellspacing="0" border="0"><tr><td style="padding-right:0px" title ="View Map"><a
href="XXX" onmouseover=\'xpe("kli11o");\' onmouseout=\'xpe("kli11n");\'
class="mapbutton"><img id="xpi_kli11" src="'+vbImgPath+'/btkli11_0.gif" name="vbkli11"
width="197" height="66" border="0" alt="View Map" /></a></td></tr></table>');
vbkli11n=xppr('kli11_0.gif');
vbkli11o=xppr('kli11_1.gif');
var btIdPref="vb";
function xppr(im){
var i=new Image;
i.src=vbImgPath+"bt"+im;return i;
}
function xpe(id){
x=id.substring(0,id.length-1);
if(document[btIdPref+x]){
document[btIdPref+x].src=eval(btIdPref+id+".src");
}
}
If I create another array of the required links similar to:
var link=new Array();
link[1]="http://g.co/maps/8ppb8";
link[2]="etc...
how can I get the button's js to use the link?
(And please don't tell me I should be using a database for this).
Hope this is clear.
Steve
You could use:
window.location
For example:
onclick="window.loaction = 'XXX'"
I hope that's clear enough. If not I can edit if you need more information.
EDIT:
After reading the comments I hope this example helps you out:
<html>
<head>
<script language="JavaScript">
link = ['http://www.google.com', 'http://www.stackoverflow.com', 'http://www.bing.com']
function changeLocation(index) {
window.location = link[index]
}
</script>
</head>
<body >
<table>
<tbody>
<tr>
<td>
<a onclick="changeLocation(0)">Google</a>
</td>
</tr>
<tr>
<td>
<a onclick="changeLocation(1)">Stackoverflow</a>
</td>
</tr>
<tr>
<td>
<a onclick="changeLocation(2)">Bing</a>
</td>
</tr>
</tbody>
</table>
</body>

Categories