Trouble Figuring Out Behavior of HTML page with Append Child - javascript

Recently I've been developing an application that allows a user to enter a stock symbol on a webpage and it returns some data from the Yahoo finance API. I can get the data fine and want to display it in a table. But right when I call appendChild it displays the data perfectly on the page and then in about a second it is gone! I figured I would post this question here since I've never seen anything like this before. Also the other strange thing that if I don't have the confirm message right after the appendChild line it seems like it doesn't even go to the callback method at all. Can anyone help me figure out what is going on and why my data shows up for a second and then is gone the next? Does this have something to do with the HTML tree?
Here is my complete code:
<!DOCTYPE html>
<html>
<head>
<title>Public Stock Ticker and Selection</title>
<meta charset="utf-8"</meta>
<link rel="stylesheet" type="text/css" href="mashsheet.css">
<div id="headerdiv">Diversified Stocks and Securities</b>
<div id="imagediv">
<img id="cnnimg" src="cnn.jpg" alt="Sorry" height="80" width="140"/img>
<img id="appleimg" src="apple.jpg" alt="No Apple" height="100" width="120"/img>
<img id="microimg" src="microsoft.jpg" alt="No Micro" height="100" width="150"/img>
<img id="amaimg" src="amazon.jpg" alt="No amazon" height="70" width="200"/img>
<img id="nationimg" src="nationwide.jpg" alt="No nationwide" height="50" width="240"/img>
<img id="huntingtonimg" src="huntington.jpg" alt="No huntington" height="70" width="160"/img>
<img id="ciscoimg" src="cisco.gif" alt="No cisco" height="70" width="160"/img>
<img id="ibmimg" src="ibm.jpg" alt="No ibm" height="70" width="160"/img>
</div>
<p id="headdescription"> - A quick and easy place to find up to date stock information about your favorite companies!</p>
</div>
</head>
<body>
<p>Enter the name of the stock you are interested in below and then click the submit button
to get back a wealth of information including trades, gains, losses, and more.</b></p>
<form id="stockInput">
Stock Name: <input type="text" id="stockTextBox">
<input type="submit" id="submitButton" value="Submit">
</form>
</b>
<table id="stocktable"
<tr> <th scope="col">Stock Name</th>
<th scope="col">Price</th>
<th scope="col">Symbol</th>
<th scope="col">Ts</th>
<th scope="col">Type of Stock</th>
<th scope="col">UTC Time</th>
<th scope="col">Volume</th>
</tr>
<tr> <th id="name" scope="row"></th>
<th id="price" scope="row"></th>
<th id="symbol" scope="row"></th>
<th id="ts" scope="row"></th>
<th id="typeofstock" scope="row"></th>
<th id="utctime" scope="row"></th>
<th id="volume" scope="row"></th>
</tr>
</table>
<label id="stockLabel"></label>
<script>
var submitButton = document.getElementById("submitButton");
submitButton.addEventListener('click', actionPerformed, false);
function actionPerformed(e)
{
var textValue = document.getElementById("stockTextBox").value;
var script = document.createElement('script');
script.setAttribute('src',"http://finance.yahoo.com/webservice/v1/symbols/"+textValue+"/quote?format=json&callback=myCallBack");
document.body.appendChild(script);
confirm("You got information for " + textValue + "stock!");
}
function myCallBack(data)
{
document.getElementById("name").innerHTML = data.list.resources[0].resource.fields.name;
document.getElementById("price").innerHTML = data.list.resources[0].resource.fields.price;
document.getElementById("symbol").innerHTML = data.list.resources[0].resource.fields.symbol;
document.getElementById("ts").innerHTML = data.list.resources[0].resource.fields.ts;
document.getElementById("typeofstock").innerHTML = data.list.resources[0].resource.fields.type;
document.getElementById("utctime").innerHTML = data.list.resources[0].resource.fields.utctime;
document.getElementById("volume").innerHTML = data.list.resources[0].resource.fields.volume;
}
</script>
</body>
</html>

<input type="submit" id="submitButton" value="Submit">
This is a submit button. When you press a submit button and don't cancel it, it submits the page. Your <form> does not have an action, therefore the current URI is used. Your <form> does not have a method, therefore GET is used. Your <input> does not have a name, therefore all you see change is a ? added to the URI.

Try putting the confirmation message in a timeout...
document.body.appendChild(script);
setTimeout(function(){
confirm("You got information for " + textValue + "stock!");
}, 0);

Related

Execute JavaScript page refresh on postgres database entry addition

I have a Spring web app, where entries are added every 10 seconds to the database. I'd like my page to automatically reload when a new entry is added to the database. So far I have come up with such code:
function contentRefresh() {
$.ajax({
url: "/refresh",
success: function(data) {
console.log(data);
$("#main-content").html(data);
}
});
}
And the data that is returned from the controller is a html fragment:
#RequestMapping("/refresh")
public String refreshPage(Model model, Pageable pageable){
PageWrapper<NetworkHashrate> page = new PageWrapper<NetworkHashrate>(netService.getAllNetworks(pageable), "");
model.addAttribute("page", page);
model.addAttribute("networkHashrates", page.getContent());
return "main :: table-content";
}
And a .html that contains refreshed fragment:
<div class="table-responsive" id="main-content" th:fragment="table-content">
<table class="table table-hover ">
<thead class="thead-inverse">
<tr>
<th class="col-md-2 text-center">Network Id</th>
<th class="col-md-2 text-center">Rep_date</th>
<th class="col-md-2 text-center">Hashrate</th>
</tr>
</thead>
<tr style="cursor: pointer;" th:each="networkHashrate : ${networkHashrates}" th:onclick="'javascript:openPoolModal(\''+ ${networkHashrate.id} + '\');'">
<td class="text-center" th:text="${networkHashrate.id}"> Sample id</td>
<td class="text-center" th:text="${networkHashrate.rep_date}">Sample rep-date</td>
<td class="text-center" th:text="${networkHashrate.hashrate}">Sample hashrate</td>
</td>
</tr>
</table>
<button type="button" class="btn btn-success" th:onclick="'javascript:contentRefresh();'">Refresh!</button>
<div class="text-center" id="stat">
<div class="pagination"><p>Displaying <span class="badge" th:text="${page.size * (page.number-1) + 1}"></span> -
<span class="badge" th:text="${page.lastPage ? page.totalElements : page.size * (page.number-1)+ page.size}"></span> of
<span class="badge" th:text="${page.totalElements}"></span> total records</p>
</div>
</div>
</div>
Earlier, I've been refreshing the page via <meta http-equiv="refresh" content="60" /> ...but I've been told that's a bad approach. I have tested the JS code with button and it seems to work, but the refresh thing scares me... How do I refresh the page based on entry addition to the database?
I have added a setInterval to my JS script like:
setInterval("contentRefresh();", 10000 );
Is not a hard refresh, but an Ajax call to reload content, so I guess that works.

jQuery only execute .append once

I want to add an extra row with some extra calculations to an existing table. The table doesn't have a header tag, it's just figuring out what CSS to apply by itself. I'm adding an extra header via the code found below. Right now it's adding the header twice. The (edited) code of the table looks like this:
<!--This code is in a <form> with the id="train_form", hence the usage in the jQuery code-->
<table class="vis" style="width: 100%">
<tbody>
<tr>
<th style="width: 20%">Eenheid</th>
<th style="min-width: 400px">Behoefte</th>
<th>In het dorp/Totaal</th>
<th style="width: 120px">Rekruteren</th>
<th style="width: 80px">To Do:</th>
</tr>
<tr class="row_a">
<td class="nowrap">
<a href="#" class="unit_link" data-unit="spear">
<img src="image.png" style="vertical-align: middle" alt="" class="">
Speervechter
</a>
</td>
</tr>
<!-- There are 3 more entries here, but to not be too long I've removed them. They are not really necessary-->
<tr>
<td colspan="3">
</td>
<td>
<input class="btn btn-recruit" style="float: inherit" type="submit" value="Rekruteren" tabindex="11">
</td>
<th style="width: 80px">To Do:</th>
</tr>
</tbody>
</table>
The lines <th style="width: 80px">To Do:</th> are added by my script. The problem is that it also adds it to the last <td>. I've looked at quite a few 'solutions', but they are not helping. It's still adding the code twice (see screenshot below).
The code that I'm using to add the lines:
$(function() {
var done = false;
if (!done) {
$("#train_form > .vis > tbody > tr:not(.row_a, .row_b)").one().append("<th style='width: 80px'>To Do:</th>");
done = true;
};
}).one();
As you can see I've tried using the .one() methods, and I've tried using a bool for it. Both don't work, since this code still gives the table seen in the image above.
Just to be clear, I have no control over the source, this is a script for an online browser game.
What am I doing wrong?
I think you want $.first() instead of $.one():
$("#train_form > .vis > thead > tr:not(.row_a, .row_b)")
.first()
.append("<th style='width: 80px'>To Do:</th>");

jQuery overriding hyperlinks on table's td values

I have a table as below and am trying to open a pop-up window with the link '/ledesInvoiceErrors.do?InvoiceId='+parentInstanceId' when user clicks on Invoice number columns of table (INV1 and INV2) instead of going to the hyper link associated with invoice number fields.
http://jsfiddle.net/pmgguwob/3/
<div class="listTable expanded">
<table class="searchResults {id:321}">
<thead>
<tr class="tipAdded">
<th class="first unsortable ui-state-default ui-state-hover ui-state-active"></th>
<th data-name="Invoice Number" class="typeString ui-state-default ui-state-hover sort asc ui-state-active" id="sort_invoiceNumber">
Invoice Number
</th>
<th data-name="Invoice Total" class="typeMoney last ui-state-default ui-state-hover ui-state-active sort" id="sort_invoiceTotal">
Invoice Total
</th>
</tr>
</thead>
<tbody class="">
<tr class="tipAdded">
<td class="first">
<div style="display:none" class="renderedValue">
INV1
</div>
<input value="65" name="invoices0.id" type="hidden" class="check"/>
</td>
<td class="typeString ">
<div class="data typeString"><a tooltip="" class="listLink " title="" href="/CP/show.do?parentInstanceId=51;parentFieldName=invoices">
INV1
</a>
</div>
</td>
<td class="typeMoney ">
<div class="data typeMoney">
15.25 USD
</div>
</td>
</tr>
<tr class="tipAdded">
<td class="first">
<div style="display:none" class="renderedValue">
INV2
</div>
<input value="66" name="invoices1.id" type="hidden" class="check"/>
</td>
<td class="typeString ">
<div class="data typeString"><a tooltip="" class="listLink " title="" href="/CP/show.do?parentInstanceId=55;parentFieldName=invoices">
INV2
</a>
</div>
</td>
<td class="typeMoney ">
<div class="data typeMoney">
111.25 USD
</div>
</td>
</tr>
</tbody>
</table>
Am a very beginner of jQuery and I dont really know how to achieve this. Could anyone please me with this?
Note: I dont have liberty of modifying the hyperlinks associated with Invoice number fields since these links are generated from our internal framework. but I can embed jquery script on my page to override the hyperlinks
SOLUTION UPDATED
http://jsfiddle.net/pmgguwob/10/
To override your hyperlink's behaviour, you can do something along the lines of:
$(function(){
// you may have to narrow down the selector here to a specific class or 'td'
$(".searchResults a").on('click', function(e){
e.preventDefault();
var url = $(this).attr('href');
window.open(url, 'window name', 'window settings');
return false;
});
});
Updated Fiddle
In this case, something like this (fiddle):
$("a").click(function (e) {
e.preventDefault();
var mills = (new Date).getTime();
window.open($(this).attr("href"), mills);
//$("body").append("#" + $(this).attr("href") + "#");
});
I'm using mills to give each window a new handle, so you don't reuse a window and potentially confuse your user by reloading a window that's hidden from them. The last line is just to show the URL it's using for testing; you might want to massage that value a little, but I believe it's right as is.
I know window.open isn't new and cool, but its options let you control the new window's appearance with likely enough granularity. You could jQuery that up instead if you wanted.

Load a script for the elements of an array

I am trying to create a dynamic form where you can order something.
In basic form, we have one row, but if you want to order more things we can dynamically without reloading the page, add the new row. So far everything is working properly for me, but in this form we have two dropdown ("input select") lists. These drop-down lists are dependent on each other and do not know how to load them the relationship between them and the option of choice. I have tried many different examples from the internet, but always work correctly only the first default row. Dynamically created rows are no longer dependent on one another.
If I am doing something wrong, and you know a better way, please show me this way.
I ask you for help, because I really depend on that. Thank you in advance. ;)
Update
Hmm .. Now I understand, but I do not know much how to use it in my web page code. Will show you the web page code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><br>
<html><br>
<head><br>
<title>Dynamic forms</title><br>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><br>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script><br>
<script type="text/javascript" src="http://jquery.bassistance.de/validate/jquery.validate.js"></script><br>
<script language="javascript" src="chainedselects.js"></script><br>
<script language="javascript" src="exampleconfig2.js"></script><br>
</head>
<body onload="initListGroup('vehicles', document.formm.elements['group[]'], document.formm.elements['product[]'], 'cs')">
<script type="text/javascript">
$(document).ready(function(){
var i = 2;
var templateRow = jQuery.format($("#template").val());
function addRow() {
var ii = i++;
$(templateRow(ii)).appendTo("#listProducts tbody");
$("#removeProduct_" + ii).click(function(){
$("#row_" + ii).remove();
});
}
$("#addProduct").click(addRow);
});
</script>
<!-- Template row in the table -->
<textarea id="template" style="display:none;" cols="1" rows="1">
<tr id="row_{0}" valign="top">
<td>{0}.</td>
<td><select name="group[]" style="width: 100%;"></select></td>
<td><select name="product[]" style="width: 100%;"></select></td>
<td><input type="text" name="price[]" style="width: 100px;"></td>
<td><input type="text" name="quantity[]" style="width: 97%;"></td>
<td><img src="remove.png" id="removeProduct_{0}" alt="remove"></td>
</tr>
</textarea>
<!-- This summary table -->
<form name="formm" action="parser.php" method="post">
<table id="listProducts" name="list">
<thead>
<tr>
<th>Nr</th>
<th>Group</th>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
<th>+/-</th>
</tr>
</thead>
<tfoot>
<tr>
<th colspan="3" align="left">
<input type="submit" name="send" value="Send" style="width: 100px;">
</th>
</tr>
</tfoot>
<tbody>
<tr valign="top">
<td>1.</td>
<td><select name="group[]" style="width: 100%;"></select></td>
<td><select name="product[]" style="width: 100%;"></select></td>
<td><input type="text" name="price[]" style="width: 100px;"></td>
<td><input type="text" name="quantity[]" style="width: 97%;"></td>
<td><img src="add.png" id="addProduct" alt="add"></td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
This is a parser.php:
<?php
$data = array();
$data['Groups'] = $_POST['group'];
$data['Products'] = $_POST['product'];
$data['Prices'] = $_POST['price'];
$data['Quantity'] = $_POST['quantity'];
$result = print_r($data,true);
echo "<pre>$result</pre>";
?>
Here is link to all code.
The click events are not attached to the newly created rows, so you need to make sure that any new rows, after they are created have click events attached to them.
function dependantFunction() {
/* code */
}
function addNewRow() {
var a=document.createElement("div");
var b=document.createElement("img");
b.src="images/add.png";
b.addEventListener("click", dependantFunction, false);
a.appendChild(b);
document.getElementById("rowholder").append(a);
}
Then all new rows should have all the necessary events attached to them.

Don't understand jquery - setting equal height contained divs

I am trying to set two side-by-side divs contained by a single larger div to equal column height. I am trying to use the following jquery script:
<script type="text/javascript" language="javascript">
function pageLoad() {
$(document).ready(function() {
setEqualHeight($(".instructionsParent > div"));
});
}
function setEqualHeight(columns) {
var tallestColumn = 0;
columns.each(function() {
currentHeight = $(this).height();
if(currentHeight > tallestColumn) {
tallestColumn = currentHeight;
}
});
columns.height(tallestColumn);
}
</script>
Then the following are my DIV's:
<div class="instructionsParent borderDiv borderTable0" style="overflow:hidden">
<div class="instructionsLeft" style="float:left;width:49.5%">
</div>
<div class="instructionsRight" style="float:right;width:49.5%">
</div>
</div>
The jquery is running and appears to be returning the largest height (451), but doesn't seem to apply it to the two divs. I don't know much jquery or javascript and don't understand the following: "setEqualHeight($(".instructionsParent > div"));"
Could it be that I have that coded incorrectly?
Thank you,
James
Ok, here is the entire subform which is my entire page really (I have two subforms on the page with one visible and the other not:
<%# Control Language="VB" AutoEventWireup="false" CodeFile="ActivexInstructionsSubForm.ascx.vb" Inherits="Controls_ActivexInstructionsSubForm" %>
<div class="instructionsParent borderDiv borderTable0" style="overflow:hidden">
<div class="instructionsLeft" style="float:left;width:49.5%">
<table cellspacing="0" class="borderTable0" width="100%" style="height:430px;" >
<tr>
<td align="center">
<br />
<h3 style="font-family:Arial;color:#17238C">"The Important Stuff"</h3>
</td>
</tr>
<tr valign="top">
<td align="center">
<table border="0" cellpadding="1" cellspacing="0"
style="border-collapse: collapse;">
<tr>
<td>
<table border="0" cellpadding="0">
<tr>
<td colspan="2" style="text-align:left;font-family:Arial;font-weight:bold;color:#17238C">
<p style="font-size:11pt"><strong style="text-decoration: underline;font-size:11pt;font-style:normal">If this is the first time</strong> you've used our downloads, you now can see a
skinny information bar at the top of the page.
Click it, and select "Install ActiveX Control" from the dropdown menu.
Then, click "Install" when you see the new dialog box appear.
This does not collect info about you or hurt your machine.
</p>
</td>
</tr>
<tr>
<td colspan="2">
</td>
</tr>
<tr>
<td colspan="2" align="center">
<script type="text/javascript">
//Create JavaScript object that will embed File Downloader to the page
var fd = new FileDownloaderWriter("FileDownloader", 172, 28);
//For ActiveX control full path to CAB file (including file name) should be specified
fd.activeXControlCodeBase = "aurigma/FileDownloader2.cab";
fd.activeXControlVersion = "2,0,16,0";
//Set the Download button text
fd.addParam("ButtonDownloadText", "Proceed With Download");
//Set the Download button background color
//fd.addParam("BackgroundColor", "#E0EBFF");
fd.addParam("BackgroundColor", "White");
//Set the Download button regular image
fd.addParam("ButtonDownloadImageFormat", "width=172;height=28;BackgroundColor=#17238C;" +
"urlNormal=App_Themes/Default/images/BtnProceedDownloadA.jpg;" +
"urlDisabled=App_Themes/Default/images/BtnProceedDownloadA.jpg");
//Set license key
fd.addParam("LicenseKey", "888822-12222-D8444-111122-55555");
//Set reconnect attampts count
fd.addParam("ReconnectAttemptsCount", "360");
//Set reconnect timeout value (30000 = 10 seconds)
fd.addParam("ReconnectTimeOut", "10000");
//Configure URL from which the file list will be downloaded
//Change this path if necessary
//fd.addParam("FileList", "aurigma/filelist.txt");
//The following listener will perform some actions when the file list is about to be downloaded
fd.addEventListener("DownloadStep", "FileDownloader_DownloadStep");
//The following listener will perform some actions when download of a single file is finished
fd.addEventListener("DownloadItemComplete", "onDownloadItemComplete");
//The following listener will perform some actions when download process is complete
fd.addEventListener("DownloadComplete", "onDownloadComplete");
//The following listener will perform some actions when a general error is detected
//fd.addEventListener("Error", "onError");
//Add page load listener
//fd.fullPageLoadListenerName = "fullPageLoad";
//Set instructions property
fd.instructionsEnabled = false;
//Tell File Downloader writer object to generate all necessary HTML code to embed File Downloader into the page
fd.writeHtml();
</script>
<asp:ImageButton ID="BtnReturnHome" runat="server" AlternateText="Return to Home Page"
ImageUrl="~/App_Themes/Default/images/BtnReturnHomeS.jpg">
</asp:ImageButton>
</td>
</tr>
<tr>
<td colspan="2">
</td>
</tr>
<tr>
<td colspan="2" style="text-align:left;font-family:Arial;font-weight:normal;font-style:italic;color:#17238C">
<p style="font-size:10pt"><strong style="text-decoration: underline;font-size:11pt;font-style:normal">Why do I need this?</strong> <strong>
This tiny control-program is only installed ONCE on a given machine,
and is there to assist with all future downloads.
It allows you to download a batch of several files at once, save
them wherever you wish, AND keeps track of the download progress. If your internet connection glitches, the
download will *automatically restart* (after a couple of minutes)
from where it left off, once the internet connection is restored, presuming that your computer remains powered on.
This is a very important feature, since these are BIG files that may take
several hours to download if you have a relatively slow internet connection.</strong>
</p>
</td>
</tr>
<tr>
<td colspan="2">
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
<div class="instructionsRight" style="float:right;width:49.5%">
<table cellspacing="0" width="100%" class="borderTable0" style="height:430px;">
<tr>
<td align="center">
<br style="height:20px" />
<h4 style="color:#17238C">Additional Info</h4>
</td>
</tr>
<tr valign="top">
<td align="center">
<table border="0" cellpadding="1" cellspacing="0"
style="border-collapse: collapse;">
<tr>
<td>
<table border="0" cellpadding="0">
<tr>
<td colspan="2" style="text-align:left;font-family:Arial;font-weight:normal;font-style:normal;color:#17238C">
<p style="font-size:9pt"><strong style="text-decoration: underline;font-size:11pt;font-style:normal">Worst-case scenario</strong>: <strong>
If the transfer fails because your computer shut down from a power-outage, there may be a temporary file left on your
machine - but the next time you start the download, it automatically cleans up what was left from the aborted transfer.
If you tend to get hit by electric power outages more often than normal, we recommend that you purchase a battery-backup UPS
(Uninterruptible Power Supply) that has at least 1500VA capacity so that the computer AND your modem AND router can remain
powered-up for several hours when the power goes out. Start the download before going to bed, and TURN OFF the monitor
during that process, so that the UPS would not have to feed it if a power outage hits.</strong>
</p>
</td>
</tr>
<tr>
<td colspan="2">
</td>
</tr>
<tr>
<td colspan="2" style="text-align:left;font-family:Arial;font-weight:normal;font-style:normal;color:#17238C">
<p style="font-size:9pt"><strong style="text-decoration: underline;font-size:11pt;font-style:normal">Gotta-shut-down scenario</strong>: <strong>
If you are in the midst of a long download session, but for some reason you must interrupt it and turn off your computer
a while, then if you want to resume the download from where you left off, be sure to HIBERNATE your machine rather than
doing a simple shutdown. You can set this up from Control Panel > Power Options > Hibernate Tab. There will be a button
on your keyboard somewhere that activates hibernation (sometimes called "sleep"). It takes a complete "RAM snapshot" of
what is going on, so that the next time you start the computer, it resumes exactly where it left off (it may take a few
minutes after restart for the download to auto-resume).</strong>
</p>
</td>
</tr>
<tr>
<td colspan="2" style="height:24px">
</td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
</div>
Removing the pageload function worked for me. The script on my working page reads:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
setEqualHeight($(".instructionsParent > div"));
});
function setEqualHeight(columns) {
console.log("here")
var tallestColumn = 0;
columns.each(function() {
currentHeight = $(this).height();
if(currentHeight > tallestColumn) {
tallestColumn = currentHeight;
}
});
columns.height(tallestColumn);
}
</script>
Try removing the pageLoad() function (I don't think you were calling it).
See :
http://paulisageek.com/tmp/jquery/equal_height.html

Categories

Resources