Fetching values from an element in an iframe on the same domain - javascript

I'm trying to condense two processes down in to one by having the two pages I need on one page using an iframe.
I have a page that contains a text area (used for sending an email) and then I have a purchase reference page that contains the details of someones purchase.
I'm trying to append an iframe of the purchase page to the bottom of my email page and then grab some data that's on it and insert it in to the text area.
EDIT: This is what I have so far:
Script one
//Grabs the selected purchase number
var purchaseNumber = window.getSelection();
purchaseNumber = purchaseNumber.toString();
var purchaseTitle;
var purchaseNumber;
function frameLoaded() {
purchaseTitle = window.frames['purchaseIframe'].contentDocument.getElementById ('listingTitle');
purchaseNumber = window.frames['purchaseIframe'].contentDocument.getElementById ('auctionSoldIdDisplay');
purchaseTitle = purchaseTitle.innerHTML;
purchaseNumber = purchaseNumber.innerHTML
var purchaseDetails = purchaseTitle + " - " + purchaseNumber;
insertText = insertText.replace("PURCHASEDETAILS", purchaseDetails);
}
if(purchaseNumber.length > 0){
var purchaseIframe = document.createElement('iframe');
purchaseIframe.src = 'http://www.mysite.co.nz/Admin/Listing/PurchaseDisplay.aspx?asid=' + purchaseNumber + '&submit1=++GO++';
purchaseIframe.setAttribute("height","1000");
purchaseIframe.setAttribute("width","100%");
purchaseIframe.setAttribute("id","purchaseIframe");
purchaseIframe.setAttribute("onload", "frameLoaded();");
void(document.body.appendChild(purchaseIframe));
alert(purchaseNumber);
}
Script Two
//Gather the selected template
var selectedTxt = document.getElementById('txtEmailText').value;
//Change the selected txt to a string
var insertText = selectedTxt.toString();
var purchaseTitle = window.frames['purchaseIframe'].contentDocument.getElementById ('listingTitle');
var purchaseNumber = window.frames['purchaseIframe'].contentDocument.getElementById ('auctionSoldIdDisplay');
purchaseTitle = purchaseTitle.innerHTML;
purchaseNumber = purchaseNumber.innerHTML
var purchaseDetails = purchaseTitle + " - " + purchaseNumber;
insertText = insertText.replace("PURCHASEDETAILS", purchaseDetails);
//Pasting the variable in to the textarea
document.getElementById('txtEmailText').value = insertText;
Effectively I am highlighting the purchase reference number on the page then executing this script to open the purchase page using the highlighted number. I am then grabbing the text values of the elements I need and pasting them in to the text area.
I'm still pretty new to javascript and am teaching myself as I go.
If i run the above scripts one after the other then it works like a charm, however if I try to run them together with the second in an onload() function set to the iframe then it won't.
Any help would be greatly appreciated or if you could point me in the direction of an article to help.

My first thought is that the iframe is not fully loaded before you try to get the values from it. My thought would be to try adding an onload event to your iframe and then when it loads invoke a function that grabs the value.
I would add purchaseIframe.setAttribute("onload", "frameLoaded();"); to your purchaseIframe block and then add the frameLoaded() function to your script. something like:
function frameLoaded() {
var purchaseTitle = window.frames[0].document.getElementById("listingTitle" );
var purchaseNumber = window.frames[0].document.getElementById("auctionSoldIdDisplay");
console.log(purchaseTitle.innerHTML);
console.log(purchaseNumber.innnerHTML);
}
And see if something like that grabs the right values. If it does than you can plug it in where you need it.
Am I understanding your problem correctly?

Related

How to Decode htmlentities in yui TextAreaCellEditor

I am facing problem with yui TextAreaCellEditor.
Below yui statements opens the editor with save and Cancel button on clicking the yui column.
var myTextareaCellEditor = new YAHOO.widget.TextareaCellEditor();
var myColumnDefs = [
{key:"title",label:"Title", sortable:true ,editor: myTextareaCellEditor},
];
Now my problem is when ever I specify title and save in database for example my title is "text&data<new>".
It is properly getting saving but when I open the editor containing the title text.
It display like "text&data<new>".
I wanted to remove html entities from editor.
Any help is very much appreciated.
TextareaCellEditor has a Event called "Focus", When the editor is initailized and focus is on it, the Focus function is called, You can make use of it.
var myTextareaCellEditor = new YAHOO.widget.TextareaCellEditor({
focus:function(e){
var textVal = myTextareaCellEditor.textarea.value;
textVal = decodeTEXT(textVal) ;
myTextareaCellEditor.textarea.value = textVal;
}
});
myTextareaCellEditor.textarea.value : will give the value that appears in the text area. This value you can decode using the decodeText() function and replace the textarea value.
function decodeTEXT(textVal){
textVal = textVal.replace(/&/g, '&');
textVal = textVal.replace(/>/g, '>');
textVal = textVal.replace(/</g, '<');
textVal = textVal.replace(/"/g, '"');
textVal = textVal.replace(/'/g, "'");
return textVal;
}
Hope this helps. Enjoy coding :)

Javascript: inserting a variable as a parameter

I am looking at getting my "NodeNumber" variable into the parameter of my loadSynchPage function.
my code looks at the name of the page (e.g. page.htm from http://www.example.com/tree/page.htm) and after a series of lines gives a "NodeNumber". I would like the page to work out the NodeNumber and put it into the function when the page loads.
So I'd guess it would look something like this:
<BODY onload="loadSynchPage(NodeNumber);">
I have got my code to output the NodeNumber using a button with onlick.
I have also got the loadSynchPage(linkID) function, to work using a button with onclick where I enter the number myself. button and have also got a variable which I predefine to work; but I can't get it to read my "NodeNumber" and I have spent 2 days trying to figure this out.
Here is my code:
<script>
function variables() {
//Getting the page's name from the URL
PageName = location.pathname.split("/").slice(-1);
document.getElementById("PageName").innerHTML = PageName;
//Converting the page name into a string
PageNameString = String(PageName);
document.getElementById("PageNameString").innerHTML = PageNameString;
//Converting the string of the page name, into it's length
PageLength = PageNameString.length;
document.getElementById("PageLength").innerHTML = PageLength;
//Setting the DemoFramesetNodes.js as a variable (Copy and Paste in - needs to have no " and be on one line)
TextFromDemoFramesetNodesJS = "foldersTree = gFld(<i>Page 1 Title</i>, page1.htm)//000foldersTree.treeID = Framesetaux1 = insFld(foldersTree, gFld(Page 2 Title, page 2.htm)) //001insDoc(aux1, gLnk(R, Page 3 Title, Page3.htm)) //002aux1 = insFld(foldersTree, gFld(Page 4 Title, Page4.htm)) //003insDoc(aux1, gLnk(R, Page 5 Title, Page5.htm)) //004";
//Need to set the difference BETWEEN the "m" in htm and the start of the number
//e.g. page2.htm)) //001
CharacterDifference = "5";
document.getElementById("CharacterDifference").innerHTML = CharacterDifference;
//Need to find the location of the page's name from the DemoFramsetNodes
PageNameLocation = TextFromDemoFramesetNodesJS.lastIndexOf(PageNameString);
document.getElementById("PageNameLocation").innerHTML = PageNameLocation;
//Need to convert all variables to be added into numbers
PageNameLocationNumber = Number(PageNameLocation);
PageLengthNumber = Number(PageLength);
CharacterDifferenceNumber = Number(CharacterDifference);
document.getElementById("CharacterDifferenceNumber").innerHTML = CharacterDifferenceNumber;
//Add the variables to give us the start location of the Node Number
NodeNumberStart = PageNameLocationNumber + PageLengthNumber + CharacterDifferenceNumber;
document.getElementById("NodeNumberStart").innerHTML = NodeNumberStart;
//Add the variables to give us the end location of the Node Number
NodeNumberEnd = PageNameLocationNumber + PageLengthNumber + CharacterDifferenceNumber + 3;
document.getElementById("NodeNumberEnd").innerHTML = NodeNumberEnd;
//this gives us the Node Number that we want
NodeNumber = TextFromDemoFramesetNodesJS.substring(NodeNumberStart, NodeNumberEnd);
document.getElementById("NodeNumber").innerHTML = NodeNumber;
}
var avar=Number(window.NodeNumber);
//window.NodeNumber;
function loadSynchPage(linkID) {
var folderObj;
docObj = parent.treeframe.findObj(linkID);
docObj.forceOpeningOfAncestorFolders();
parent.treeframe.HightlightNode(linkID,docObj.link,'basefrm');
if (typeof parent.treeframe.document.body != "undefined") // To handle scrolling not working with NS4
parent.treeframe.document.body.scrollTop=docObj.navObj.offsetTop
}
//myvar=Number(NodeNumber);
// function loadnode(){
// document.getElementById('loadSynchPage').onclick=function(){loadSynchPage(myvar);};
// var myvar=15;
//function init(){
// document.getElementById('EditBanner').onclick=function(){EditBanner(myvar);};
// }
</script>
</head>
<BODY>
<button onclick="javascript:settingvariables();">Page Highlight1</button>
<button onclick="javascript:loadSynchPage(avar);">Page Highlight2</button>
Page Name: <p id="PageName"></p>
Page Name String: <p id="PageNameString"></p>
Page Length: <p id="PageLength"></p>
Character Difference: <p id="CharacterDifference"></p>
Page Name Location: <p id="PageNameLocation"></p>
Character Difference Number:<p id="CharacterDifferenceNumber"></p>
Node Number Start: <p id="NodeNumberStart"></p>
Node Number End: <p id="NodeNumberEnd"></p>
Node Number: <p id="NodeNumber"></p>
As you can see from the "//" near the bottom, I have already tried some different ways from other questions on stackoverflow - I am sure I have tried everything and am missing something really simple :/
I have also taken out the "var" before setting things like PageName and NodeNumber after w3 said that this would then allow them to become global variables?
To give more information:
The code is based on TreeView - it has a tree with nodes on the left and you click on the nodes to open the page in the right hand frame. However clicking on a link from a page in the right page to a different page doesn't update the highlighting on the node and that is why I am trying to do this (onload).
EDIT: If possible I would also like to get the code into an external .js and reference it as I have multiple pages (I tried this for a few hours last week with different, working code, but also couldn't get this to work either).
All you need is:
window.onload = function() {
loadSynchPage(NodeNumber);
};
Or the onload in body tag, the problem you have is that it doesn't work in the sandbox in this snippet:
Uncaught SecurityError: Sandbox access violation: Blocked a frame at
"http://stacksnippets.net" from accessing a frame at
"http://stackoverflow.com". The frame requesting access is sandboxed
and lacks the "allow-same-origin" flag.
function variables() {
//Getting the page's name from the URL
PageName = location.pathname.split("/").slice(-1);
document.getElementById("PageName").innerHTML = PageName;
//Converting the page name into a string
PageNameString = String(PageName);
document.getElementById("PageNameString").innerHTML = PageNameString;
//Converting the string of the page name, into it's length
PageLength = PageNameString.length;
document.getElementById("PageLength").innerHTML = PageLength;
//Setting the DemoFramesetNodes.js as a variable (Copy and Paste in - needs to have no " and be on one line)
TextFromDemoFramesetNodesJS = "foldersTree = gFld(<i>Page 1 Title</i>, page1.htm)//000foldersTree.treeID = Framesetaux1 = insFld(foldersTree, gFld(Page 2 Title, page 2.htm)) //001insDoc(aux1, gLnk(R, Page 3 Title, Page3.htm)) //002aux1 = insFld(foldersTree, gFld(Page 4 Title, Page4.htm)) //003insDoc(aux1, gLnk(R, Page 5 Title, Page5.htm)) //004";
//Need to set the difference BETWEEN the "m" in htm and the start of the number
//e.g. page2.htm)) //001
CharacterDifference = "5";
document.getElementById("CharacterDifference").innerHTML = CharacterDifference;
//Need to find the location of the page's name from the DemoFramsetNodes
PageNameLocation = TextFromDemoFramesetNodesJS.lastIndexOf(PageNameString);
document.getElementById("PageNameLocation").innerHTML = PageNameLocation;
//Need to convert all variables to be added into numbers
PageNameLocationNumber = Number(PageNameLocation);
PageLengthNumber = Number(PageLength);
CharacterDifferenceNumber = Number(CharacterDifference);
document.getElementById("CharacterDifferenceNumber").innerHTML = CharacterDifferenceNumber;
//Add the variables to give us the start location of the Node Number
NodeNumberStart = PageNameLocationNumber + PageLengthNumber + CharacterDifferenceNumber;
document.getElementById("NodeNumberStart").innerHTML = NodeNumberStart;
//Add the variables to give us the end location of the Node Number
NodeNumberEnd = PageNameLocationNumber + PageLengthNumber + CharacterDifferenceNumber + 3;
document.getElementById("NodeNumberEnd").innerHTML = NodeNumberEnd;
//this gives us the Node Number that we want
NodeNumber = TextFromDemoFramesetNodesJS.substring(NodeNumberStart, NodeNumberEnd);
document.getElementById("NodeNumber").innerHTML = NodeNumber;
}
var avar=Number(window.NodeNumber);
//window.NodeNumber;
function loadSynchPage(linkID) {
alert("loadSynchPage called");
var folderObj;
docObj = parent.treeframe.findObj(linkID);
docObj.forceOpeningOfAncestorFolders();
parent.treeframe.HightlightNode(linkID,docObj.link,'basefrm');
if (typeof parent.treeframe.document.body != "undefined") // To handle scrolling not working with NS4
parent.treeframe.document.body.scrollTop=docObj.navObj.offsetTop
}
loadSynchPage(NodeNumber);
//myvar=Number(NodeNumber);
// function loadnode(){
// document.getElementById('loadSynchPage').onclick=function(){loadSynchPage(myvar);};
// var myvar=15;
//function init(){
// document.getElementById('EditBanner').onclick=function(){EditBanner(myvar);};
// }
<button onclick="javascript:settingvariables();">Page Highlight1</button>
<button onclick="javascript:loadSynchPage(avar);">Page Highlight2</button>
Page Name: <p id="PageName"></p>
Page Name String: <p id="PageNameString"></p>
Page Length: <p id="PageLength"></p>
Character Difference: <p id="CharacterDifference"></p>
Page Name Location: <p id="PageNameLocation"></p>
Character Difference Number:<p id="CharacterDifferenceNumber"></p>
Node Number Start: <p id="NodeNumberStart"></p>
Node Number End: <p id="NodeNumberEnd"></p>
Node Number: <p id="NodeNumber"></p>
2nd question: Save all the script (not including the <script> tags) to myjs.js, put it to the same directory next to page.html, and remove the whole <script> block from html, and put this instead of it:
<script src="myjs.js"></script>

Modify innerHTML for table row in javascript in ie8?

I am trying to add create an editable table in HTML. So, I need to add rows, when user clicks on a button. Here is the code I am using.
//remove all old rows.
while (summaryTableElement.firstChild) {
summaryTableElement.removeChild(summaryTableElement.firstChild);
}
//add a new text area in the summary field.
summaryTableElement.innerHTML = "<textarea id='summaryTextBox' value='' onblur='saveSummary()'> </textarea> ";
This code works fine on Chrome and Mozilla. But, IE doesn't allow editing innerHTML. This HTML will be displayed inside a VB form, so I have "browser" and "webbrowser" controls available. Both of those controls use IE engine, so this code does not work there.
I have tried using firstchild.innerHTML instead so that I am not editing table row directly, and even that gave me same error.
I tried using WebKitBrowser. But, that causes an exception on load. Apparently that control uses some old method, and the method is changed. So, that control is out of question too.
Now, I am confused as to how to solve this problem?
Edit:
I found the issue with WebKitBrowser. It was specific to x86, while my project was targeting both x64 and x86. Switching it to x86 for both, worked. Although, webkit browser do not take return key values. So, I have a new problem. Pressing enter does not create a new line in table cell, and instead passes the event to vb form.
Edit:
Okay, so I tried working further with WebKitBrowser. But, that control gives me accessviolatedexception. So, I am thinking about going back to using the default browser control, for now.
As for default control, I checked further. Apparently, code works fine in IE9 and above. But, vb.net control uses some weird JS engine. So, I am receiving error only in vb control.
Here is the complete code for reference:
var summaryChanges = "";
var isSummaryClickable = true;
//creates a textbox for editing purpose and include the original summary data.
function modifySummary(id) {
var summaryTableElement; //to get the table cells so that we can access the value
var originalSummary = ""; //to hold the original summary while we create a text box
var loopCounter = 0;
if (isSummaryClickable == true) {
isSummaryClickable = false; //saves event spilling when clicked on the newly created textbox
//get the summary table id saved.
summaryTableElement = document.getElementById (id).childNodes.item(0);
//add existing data to a string to save it for later.
for (loopCounter = 0; loopCounter < summaryTableElement.childNodes.length; loopCounter++) {
originalSummary = originalSummary + summaryTableElement.childNodes.item(loopCounter).childNodes.item(0).innerHTML + "\n";
}
//remove all old rows.
while (summaryTableElement.firstChild) {
summaryTableElement.removeChild(summaryTableElement.firstChild);
}
//add a new text area in the summary field.
summaryTableElement.innerHTML = "<tr><td><textarea id='summaryTextBox' value='' onblur='saveSummary()'> </textarea></td></tr> ";
//set the width of the textbox to allow easy modification
document.getElementById("summaryTextBox").style.width = '600px';
//add original summary text to the text area and set focus
document.getElementById("summaryTextBox").value = originalSummary;
document.getElementById("summaryTextBox").focus();
}
}
// saves the updated summary data back to HTML
function saveSummary()
{
var newHTML = "";
var changesSummary;
var changesSubString = new Array();
var index = 0;
var elementToUpdate;
//get the summary table id saved.
elementToUpdate = document.getElementById("SummaryData"); //.childNodes.item(0);
//get changes from the textbox
changesSummary = document.getElementById("summaryTextBox").value;
//generate string array for separate lines from summaryChanges
changesSubString = changesSummary.split("\n");
//generate new HTML string for the summary fields
//alert(changesSubString.length);
for (index = 0; index < changesSubString.length; index++) {
newHTML = newHTML + "<tr><td class='Text' style='padding-left: 4px;padding-bottom: 4px;' id='SummaryLine" + index + "'</td>" + changesSubString[index] + "</tr>"
}
//update the HTML to the element
elementToUpdate.innerHTML = newHTML;
//allow clicking on summary table
isSummaryClickable = true;
}
function doNothing(id) {
//empty function for future use
return;
}
//this function is called from vb.net script to read the js variable.
//do not change the function definition (name or parameters or return type)
//any change will cause error in vb.net script
function jsInvokedFunction() {
var updatedHTML; // to be used by vb.net invoked function to get updated body
var testVariable = "test";
updatedHTML = document.body.innerHTML.toString();
return updatedHTML.toString();
}
I receive an error at the start of the line summaryTableElement.innerHTML = " ";
It is possible I am missing some other error, but I couldn't find any.

Reading and formatting Access data

I'm using JavaScript and HTA to read data in access database (.mdb) on local but having a small issue. My JavaScript code is like this:
function miseryBusiness() {
var box = document.getElementById("lyrics");
box.innerHTML = "";
var db = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='paramore.mdb'";
var adoConn = new ActiveXObject("ADODB.Connection");
var adoRS = new ActiveXObject("ADODB.Recordset");
adoConn.Open(db);
adoRS.Open("SELECT * from 2007_RIOT WHERE track=4", adoConn, 1, 3);
var lyrics = adoRS.Fields("lyrics").value;
box.innerText = lyrics;
adoRS.Close();
adoConn.Close();
}
I have a div in the page with id="lyrics". Function gets the specified cell's value and change's div's inner text to that value.
What I want to do is use innerHTML instead of innerText. And if I use inner HTML I get the cell's value as a single line. I want to add line breaks to the end of the each line. Also an anchor to the beginning of the text.
If I was getting the text from a .txt file I'd use
while(!lyrics.AtEndOfStream) {
box.innerHTML += '<a id="miseryBusiness">' + lyrics.ReadLine() + '<br/>';
}
but this doesn't work with access database. Or I couldn't get it to work. Any ideas?
The HTA and .mdb file I'm using: link1 link2
If the lyrics are in a Memo field with hard line-breaks then the line terminator is almost certainly <cr><lf>, so try the following:
box.innerHTML = '<a id="miseryBusiness">' + lyrics.replace(/\r\n/g, '<br/>');

Stop a page from refreshing after firing a function

I've been tasked with building a very simple app that that has a series of dropdowns in rows of 2, when 2 are selected, a simple functions concatenates the 2 values and gives an output next to them like so:
dropdown1 dropdown2 Output
What I'm trying to get is, once the second dropdown value is chosen the function runs and displays the output where it says output. But currently, what seems to happens is the output is displayed in a new window.
Here's what I have so far (HTML):
<form>
<select id="test">
<option>Arena/Quantum Barcelona LTBC</option>
<option>Arena/Quantum Spain LTES</option>
</select>
<select id="name" onchange="tryThis()">
<option>Name</option>
<option>Name1</option>
</select>
</form>
JavaScript:
function tryThis() {
var string, string1 = '';
var e = document.getElementById("test");
string = e.options[e.selectedIndex].text;
var a = document.getElementById("name");
string1 = a.options[a.selectedIndex].text;
document.write(string+'_'+string1);
}
Am I making this more difficult than it needs to be?!
That's because document.write clears the page before displaying something. You should never need to use that function.
Instead, you could append it to e.g. the body:
document.body.appendChild(
document.createTextNode(string + '_' + string2)
);
Have you noticed that your JS function is called tryThis() and on the event handler you're calling tryThsis()
However in your case I'd refrain from using document.write, good alternatives are appending to the body or having a DIV and changing the innerHTML of that DIV
First put an id on your form so that it is easier to access.
var a = (function () {
var myForm = document.getElementById("myForm"),
magic = function () {
var a = myForm.getElementsByTagName("select"),
b,
c = [];
for (b = a.length - 1; b > -1; b -= 1) {
c.push(a[b].value);
}
alert(c.join(" ") + " output");
};
myForm.onclick = magic;
}());
You were not specific as to what the extra "output" is supposed to be or how you want the data returned, but here you go. Instead of using an alert you could push the result into the value of a different form element. Do not use document.write as this cannot be deferred. If you attempt to defer a document.write operation it will replace the entirety of the body contents of the current page.

Categories

Resources