I have 2 HTML files namely a.html and b.html, One js file namely do.js.
Here are each the contents of each file:
a.html:
<head>
<script src="do.js" type="text/javascript"></script>
</head>
<body>
<button onClick = "doWork();">click me</button>
<iframe src = "b.html" id = "previewFrame"></iframe>
</body>
b.html (relevant part):
<div id = "container"></div>
do.js:
function doWork(){
var div = $('#previewFrame').contents().find('#container');
div.html("<input type = 'text' id = 'testElem' value = '12'><script>alert(document.getElementById('testElem').value);</script>");
}
When I run the above code, the content of the iframe gets replaced by the text box, however the alert fails.
I get a "type error" stating that document.getElementById... is null.
Can anyone please tell me what am I missing in the above code?
You are calling the Javascript function using document, but this object is from the parent document, not the document of the iframe, try with:
function doWork(){
var a = $('#previewFrame').contents().find('body');
a.html("<input type = 'text' id = 'testElem' value = '12'><sc"+"ript>alert($('#previewFrame').contents()[0].getElementById('testElem').value);</scr"+"ipt>");
}
See demo here.
Related
In a.html:
I have a textarea that is converted into a link after the user clicks the submit button. When the user clicks on the link they are redirected to b.html.
<textarea id="sentenceId">
</textarea>
<br>
<button type="button" id="buttonId" onclick="createLink(document.getElementById('sentenceId').value)">Submit
</button>
<p id="demo">
<a id ="link" href="b.html"></a>
</p>
In b.html:
I would like to display the original text.
In script.js:
function createLink(val) {
document.getElementById("link").innerHTML = val;
document.getElementById('buttonId').style.display = 'none';
document.getElementById('sentenceId').style.display = 'none';
}
If you want to open a new page and get the text there, you could use a post-form and an input[type="hidden"] to send the text and display it afterwards.
If you wand the link to be sendable, you'd either have to encode the text as get-parameter or save it to a database and add the id of the entry to the link.
As #Kramb already mentioned, localStorage is a possibility, but only if you stay on the same browser and both pages have the same domain.
Using localStorage
The localStorage property allows you to access a local Storage object. localStorage is similar to sessionStorage. The only difference is that, while data stored in localStorage has no expiration time, data stored in sessionStorage gets cleared when the browsing session ends—that is, when the browser is closed.
a.html
function createLink(val) {
document.getElementById("link").innerHTML = val;
document.getElementById('buttonId').style.display = 'none';
document.getElementById('sentenceId').style.display = 'none';
localStorage.setItem("textArea", val);
}
b.html
function getText(){
var textVal = localStorage.getItem("textArea");
}
Another option would be to use a query string.
a.html
function navigateTo(val){
window.href.location = "b.html?text=" + val;
}
This will pass the value of the text from textarea with the url during navigation. Once b.html has loaded, you can do the following.
b.html
function getText(){
var url = window.location.href;
var queryIndex = url.indexOf("=") + 1;
var passedText = url.substring(queryIndex);
document.getElementById('foo').value = passedText;
}
This is possible using JavaScript. You can do an AJAX call to another page on you website, and search for an element to get its content. In you're case an textarea
I wrote an example on codepen.io for you. Click here
To make things simpler im using jQuery in this example.
So how does it work?
First of, include jQuery inside the <head> tag of you're website.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
I created the following structure
structure
root
scripts
jQuery.min.js
index.js
index.html
textarea.html
Contents of index.html
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Meta -->
<meta charset="UTF-8" />
<title>My New Pen!</title>
<script type="text/javascript" src="scripts/jquery.min.js"></script>
<!-- Styles -->
<link rel="stylesheet" href="styles/index.processed.css">
</head>
<body>
<button id="clickme">To load the textarea content, click me!</button>
<div id="content">The data from the textarea will be shown here, afte you click on the button :)</div>
<!-- Scripts -->
<script src="scripts/index.js"></script>
</body>
</html>
Contents of texarea.html
<textarea id="textarea">
I am the content of the textarea inside the textarea.html file.
</textarea>
Contents of index.js
(function() {
$(document).ready(function() {
/**
* The button which triggers the ajax call
*/
var button = $("#clickme");
/**
* Register the click event
*/
button.click(function() {
$.ajax({
url: "textarea.html",
type: "GET"
}).done(function(response) {
var text = $(response).filter("#textarea").html();
$("#content").append("<br/><br/><strong>" + text + "</strong>");
});
});
});
})()
So what does index.js do exactly?
As you can see i created an Ajax call to the textarea.html file. The .done function holds the response data. The data inside it can be anything depending on the content of the textarea.html file.
$(response).filter("#textarea").html();
The above piece of code filters out the #textarea div and then gets the innerHTML using the jQuery html() function.
If you want to get the value of the textarea through the [value] attribute, you can replace above line to
$(response).filter("#textarea").val();
I believe you want to do this:
function createLink() {
var textvalue = document.getElementById('sentenceId').value;
document.getElementById("link").innerHTML = textvalue;
document.getElementById("buttonId").className ="hideme";
document.getElementById("sentenceId").className ="hideme";
}
.hideme{
display: none;
}
<textarea id="sentenceId">
</textarea>
<br>
<button id="buttonId" onclick="createLink()">Submit
</button>
<p id="demo">
<a id ="link" href="b.html"/>
</p>
I have tried to call the function using window.onload but it works only when I place it body tag as below but when I place it in the head tag (commented out) it doesn't work though the function gets called (I have put an alert and checked.)
<!DOCTYPE html5>
<html>
<head>
<script>
function onl()
{
var x=document.forms[0].elements[0].name;
document.write(x);
}
//window.onload = onl();
</script>
</head>
<body>
<form name=usern>
<input type = "text" name ="username">
<input type = "password" name ="password">
<input type ="submit" name="sybmitb">
</form>
<script>
window.onload = onl();
</script>
<div id = "txt">
</div>
</body>
</html>
It doesn't run in the head because the brackets used after the assignment cause the function to immediately be run. That mean it causes an error because the document hasn't loaded yet and so causes the form elements to be undefined.
In the head, if you change
window.onload = onl();
to
window.onload = onl;
Then it will work.
You must pass the handler function to document.load (or window.load), not the return of your function. So use document.onload = onl; instead of document.onload = onl(); (see more here : https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload)
So in result :
<!DOCTYPE html5>
<html>
<head>
<script>
function onl()
{
var x=document.forms[0].elements[0].name;
document.write(x);
}
document.onload = onl;
</script>
</head>
<body>
<form name=usern>
<input type = "text" name ="username">
<input type = "password" name ="password">
<input type ="submit" name="sybmitb">
</form>
<div id = "txt">
</div>
</body>
</html>
Regards,
Julien Q.
Edit : Sorry I misread before ;)
When you assign a function like that, you need to be sure not to invoke it. When you put parentheses on the end of a function name, it will be invoked immediately even if it's being assigned to something like the window's load event.
So, you simply have to replace onl() with onl:
window.onload = onl;
As for why it works in the body, it's because the document has pretty much finished loading when it gets to the end of the body.
Assigning onl() to the window's onload property isn't erroneous because you're assigning the return value of onl(), which is undefined, to window.onload.
Also, I'd recommend not using window.onload but document.onload, because document.onload is fired when the DOM is ready, not when the files requested are ready.
I am trying to read a file in the same directory of an HTML and JavaScript file however it seems to be returning null. Below I have added the code I have from each file.
HTML File:
<html>
<!-- Code to call the Google Maps API and link style.css sheet -->
<body>
<div class="content">
<div id="googleMap"></div>
<div id="right_pane_results">hi</div>
<div id="bottom_pane_options">
<button onclick="get_parameters()">Try It</button>
</div>
</div>
</body>
<script type="text/javascript" src="./javascript.js">
</script>
</html>
JavaScript File:
function get_parameters() {
alert("hi"); // Just to let me know the function is getting called
var freader = new FileReader();
var text;
freader.onload = function(e) {
text = freader.result;
}
freader.readAsText('./test.txt', "ISO-8859-1");
text = freader.result; // To my knowledge, this should be taking the current line freader is on and storing it into text
var div = document.getElementById('bottom_pane_options');
div.innerHTML = div.innerHTML + text;
}
test.txt
Iron
Aluminum
Steel
//etc. for x number of times (depends on data I have parsed previously)
All I would like is for JavaScript to read test.txt and parse it into an array (text). The issue is, when I click the button 'Try It', the alert pops up (telling me the function is being called) and text contains null. I am running all files off my computer and all are in the exact same directory.
I'm trying to create two separate HTML documents: main.html and sufler.html. Idea is to control sufler.html page from main.html . So far I succeeded to write text and change it's font style. But font style changes only ONE time...
I need it to be able to change many times, can't understand what is going on,
because, as I understanding, every time I calling function writing(), I'm clearing all new document's content with newDoc.body.innerHTML = ''... but it seems that not... although text is changing every time.
main.html
<html>
<head>
<script type="text/javascript">
var HTMLstringPage1 = '<!DOCTYPE html><html><head><link href="stilius.css" rel="stylesheet" type="text/css" /></head><body>',
HTMLstringPage2 = '</body></html>',
HTMLstringDiv1 = '<div id="sufler"><div id="mov"><p id="flip">',
HTMLstringDiv2 = '</p></div></div>';
//NEW WINDOW OPEN--------------------------------------------------------------------------------------------------------
var newWindow = window.open('suffler.html','_blank','toolbar=no, scrollbars=no, resizable=no, height=615,width=815');
var newDoc = newWindow.document;
newDoc.write(HTMLstringPage1,HTMLstringDiv1+'Text'+HTMLstringDiv2,HTMLstringPage2);
var script = newDoc.createElement("script");
script.type = "text/javascript";
//=======================================================================================================================
//WRITING----------------------------------------------------------------------------------------------------------------
function writing(){
newText = document.getElementById("sel-1").value.replace(/\n/gi, "</br>");
fontas= document.getElementById("textFont").value;
size= document.getElementById("textSyze").value;
stylas= document.getElementById("textStyle").value;
syntax= document.getElementById("textSyntax").value;
newDoc.body.innerHTML = '';//clears old text (should clear old scripts and functions too)
newDoc.write(HTMLstringPage1,HTMLstringDiv1,newText,HTMLstringDiv2,HTMLstringPage2);//writes new text (and new scripts and functions)
var text = newDoc.createTextNode('document.getElementById("flip").style.font="'+stylas+' '+syntax+' '+size+'px '+fontas+'";');
script.appendChild(text);
newDoc.getElementsByTagName("body")[0].appendChild(script);
}
//=======================================================================================================================
</script>
</head>
<body>
<button type="button" style="background-color: #F5FF25;" onclick="writing()">Apply text</button>
</body>
</html>
Any one node can only be added to the document once. You only define script once but trying to add it to the DOM multiple times. Put the var script = ... line inside writing().
iframe is loaded dynamically into container div inside function.
With cc.text(content); I try to update #code content.
I check changed text in runtime, it's updated but on screen value remains the same.
I am not a javascript pro, so any comments are welcome:
function ShowEditor(content) {
var url = "XmlEditor/Editor.htm";
slHost.css('width', '0%');
jobPlanContainer.css('display', 'block');
frame = $('<iframe id="' + jobPlanIFrameID + '" src="' + url + '" class="frame" frameborder="0" />');
frame.appendTo(jobPlanIFrameContainer);
$(frame).load(function () {
var ifr = frame[0];
var doc = ifr.contentDocument || ifr.contentWindow.document;
var jdoc = $(doc);
var cc = jdoc.contents().find("#code");
// var tst = cc.text();
// alert(tst);
cc.text(content);
});
}
I get the text in commented code, but fail to update #code content.
iframe holds the following html where I omit details inside head and script:
<!doctype html>
<html>
<head></head>
<body>
<form>
<textarea id="code" name="code">some texts</textarea>
</form>
</body>
</html>
Your XML editor doesn't read more than once what's in the textarea.
A simple solution would be to generate in javascript the iframe content with the desired textarea content instead of loading it and then try to change the textarea content.
In fact (depending on the capacities of your XML Editor), you probably can do that directly in a generated text area instead of using a whole iframe to do it.