Iframe content to store in textarea [duplicate] - javascript

This question already has answers here:
How to change the Content of a <textarea> with JavaScript
(6 answers)
Closed 8 years ago.
Is there a way to retrieve the content from iframe and store it in textarea using pure JavaScript??
I have retireve the content from iframe using following code:
function getIframeContent(){
var frameObj = document.getElementById(frameId);
var frameContent = frameObj.contentWindow.document.body.innerHTML;
alert("frame content : "+frameContent);
}
Now how to store it in the textarea??

You can display the content of your iFrame inside your TextArea like so
document.getElementById('YourTextArea').innerHTML = frameContent;
or using the Value attribute:
document.getElementById('YourTextArea').value = frameContent;
I have done a quick demo for you using the first method.
This returns a string with any html tag in it. So for example if your iframe contains a list, the method returns an html list.
Here's the code:
<body>
<div id="frameId">
<ul>
<li id="item1">Coffee</li>
<li id="item2">Tea</li>
</ul>
</div>
<p>Click the button get the HTML content of the iframe.</p>
<textarea id="demo"></textarea><br/>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var frameContent = document.getElementById("frameId").innerHTML;
document.getElementById("demo").innerHTML = frameContent;
}
</script>
</body>

Related

Javascript innerHTML not changing div contents [duplicate]

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 4 years ago.
I am trying to change the text displayed by a div from 'hello' to 'hey' on click using innerHTML. I know my function is executed and the innerHTML is changed because I get an alert on click displaying 'hey', but on my webpage and in inspector the 'text' element's contents remain as 'hello'.
What is going on here?
code:
<html>
<head>
<script type="text/javascript">
function changehtml() {
var text = document.getElementsByClassName('text');
text.innerHTML = 'hey';
alert(text.innerHTML)
}
</script>
</head>
<body>
<div class='text' onclick='changehtml()'>
hello
</div>
</body>
</html>
Get elements by class returns an array of elements if you just want to change the one div give it and id and getElementById.
If you want to change multiple divs with that class the second snippet loops through the divs with that class and changes all of their texts.
function changehtml() {
var text = document.getElementById('x');
text.innerHTML = 'hey';
alert(text.innerHTML)
}
<html>
<head>
</head>
<body>
<div id="x" class='text' onclick='changehtml()'>
hello
</div>
</body>
</html>
function changehtml() {
var text = document.getElementsByClassName('text');
for (let i = 0; i < text.length; i++) {
text[i].innerHTML = 'hey';
}
}
<html>
<head>
</head>
<body>
<div class='text' onclick='changehtml()'>
hello
</div>
</body>
</html>
document.getElementsByClassName('text') gives you collection of nodes. So, you;ll have to loop through them to get each node. Or for this example you can use
document.getElementsByClassName('text')[0];
Or
document.querySelector('.text')
This will give you the first node with class name of text.
And make it your habit to check your console for errors, you'll probably be getting one

I want to check if parameter exist as an id in the body. how can I do that without hardcoding and using jquery? Javascript [duplicate]

This question already has answers here:
How to append text to a div element?
(12 answers)
Closed 5 years ago.
<a id="Param">This is an html element</a>
<script>
function Append(param1,text)
{
if(document.getElementById(param1))
{
return document.getElementById(param1)+text;
}
else
{
console.error("the element was not found");
}
}
var app1=Append("Anything",". yes"); //i called the append twice first is to see the output when false
var app2=Append("Param",". hi")//second is to see the output when true. I want the output to be "This is an html element. hi"
this is the code that I have. I wanted to have a function that uses two parameters. The first one is to for an html element id and the second one is for the text that will be appended to the first parameter. How can the function check if "Param" is an id without hard coding or using jquery?
A string-query might be your best bet by making the PARAM dynamic and you can change it based on what the url passes to the script. index.php?param1=myvalue
Here is a reference article I used last time I had to do it myself: https://www.joezimjs.com/javascript/3-ways-to-parse-a-query-string-in-a-url/
Respectfully,
SFR
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Lab Test 1</title>
</head>
<body>
<a id="Param">This is an html element</a>
<script>
function appendToElement(p1,p2)
{
var el=document.getElementById(p1);
if(el)
{
el.innerHTML+=p2;
return true;
}
else
{
console.error("Element with ID: "+p1+" not found");
return false;
}
}
var app1=appendToElement("Anything",". yes");
var app2=appendToElement("Param",". hi")
</script>
</body>
</html>
This is the code that I got from my professor.

javascript how to make all strings italic after hyphen?

Good morning to all
I have a question related to my big commerce products title. here I need the first part of the product's title in bold and after the hyphen or dash the second part need in italic. But problem is that the products title comes with one global variable %%GLOBAL_ProductName%% which I cannot make separated with the span tag. so can you suggest me how I can achieve the rest of strings after hyphen show in Italics with the help of javascript?
For example, check this screenshot https://www.screencast.com/t/fKy0FhByzzl
and here is big commerce website http://rp-staging2.mybigcommerce.com/categories
<li class="%%GLOBAL_AlternateClass%%">
<div class="ProductImage" data-product="%%GLOBAL_ProductId%%">
%%GLOBAL_ProductThumb%%
</div>
<div class="OutOfStockMessage InfoMessage" style="%%GLOBAL_ItemSoldOut%%">
%%SNIPPET_SideAddItemSoldOut%%
</div>
<div class="ProductActionAdd" onclick="location.href='%%GLOBAL_ProductLink%%';">
<p>%%GLOBAL_ProductName%%
</p>
<p><em class="p-price">%%GLOBAL_ProductPrice%% USD</em>
</p>
%%GLOBAL_ProductAddText%%
</div>
</li>
%%GLOBAL_ProductName%%
this variable showing products name please check screenshot and website i have provided link
Using some of the cool es6 features (array destructuring and template literals)
$(".pname").each(function () {
[beforeDash, afterDash] = $(this).text().split(" - ");
$(this).html(`${beforeDash} - <i>${afterDash}</i>`);
});
Looks like:
And if you are using jQuery in your website, you can use something like this:
$( window ).on( "load", function(){
var text = $('.text');
var x = text.text().split('-');
text.html(`${x[0]} - <i>${x[1]}<i>`);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text">
Hello - World
</div>
When ever possible do this kind of split at the server side. Because client side you will manipulate strings after loading the page. So it is not good to do at client side. But anyhow I have written jquery code to fulfill your requirement. I have written in a click event for demo purpose. Please do the logic on onload event.
$("#btn").click(function(){
$(".productName").each(function(){
var title = $(this).text();
var firstSentence = "<b>"+title.substr(0,title.indexOf('-'))+"</b>";
var secondSentence = "<i>"+title.substr(title.indexOf('-')+1)+"</i>";
var finalTitle = firstSentence+ "-" + secondSentence;
$(this).html(finalTitle);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<a class="productName"> Sample1 - Product Name1</a><br>
<a class="productName"> Sample2 - Product Name2</a><br>
<input id="btn" type="button" value="Change Format">
</body>
</html>
Check this if it helps...
https://jsfiddle.net/Lz8p11mc/1/
You need to split your product name with '-' and then add these isolated names in separate spans and then you can style these spans as you want. I have written code for simple test case , you can modify it as per your requirement.
<html>
<script>
var productName = 'ABC-XYZ';
var separatedNames = productName.split('-');
var firtsName = separatedNames[0];
var secondname = separatedNames[1];
window.onload = function() {
//when the document is finished loading, replace everything
//between the <a ...> </a> tags with the value of splitText
document.getElementById("myTag").innerHTML = '<span>'+firtsName+'</span>-<span class="secondnameCls">'+secondname+'</span>';
}
</script>
<body>
<li class="%%GLOBAL_AlternateClass%%">
<p><a id='myTag'></a></p>
</li>
</body>
</html>

Print whole HTML page including pdf file inside iframe

I've got an assignment to embed relatively small pdf file inside html page and print the entire html pade including the pdf file inside the iframe.
Here is the structure of my html page:
Here is my code:
#media print{
body * {display:block;}
.toPrint{display:block; border:0; width:100%; min-height:500px}
<body>
<button onclick="window.print()">Print</button>
<h3>MUST BE PRINTED</h3>
<p> MUST BE PRINTED</p>
<iframe class="toPrint" src="https://nett.umich.edu/sites/default/files/docs/pdf_files_scan_create_reducefilesize.pdf" style="width:100%; height:97vh;"></iframe>
<h3>MUST BE PRINTED</h3>
<p> MUST BE PRINTED</p>
</body>
Currently I'm printing the page using css #media query. But unfortunately this media query prints the pdf's first page only.
What can I do print the entire pdf file?
The reason it's not printing the whole PDF is because it's in an iframe and the height is fixed. In order to print the whole PDF you'll need the iframe height to match its content height (there should be no scrollbar on the iframe).
Another option is to print only the iframe. Add id to your iFrame:
<iframe id="toPrint" class="toPrint"></iframe>
Focus the iframe and print its content:
var pdfFrame = document.getElementById("toPrint").contentWindow;
pdfFrame.focus();
pdfFrame.print();
Try this, it includes some JS but thats always good.
HTML:
<body>
<h3>MUST BE PRINTED</h3>
<p> MUST BE PRINTED</p>
<div id="pdfRenderer"></div>
<h3>MUST BE PRINTED</h3>
<p> MUST BE PRINTED</p>
</body>
JS:
var pdf = new PDFObject({
url: "https://nett.umich.edu/sites/default/files/docs/pdf_files_scan_create_reducefilesize.pdf",
id: "pdfRendered",
pdfOpenParams: {
view: "FitH"
}
}).embed("pdfRenderer");
This should work. Let me now if i doesnt
Use https://github.com/itext/itextsharp itextsharp or https://github.com/MrRio/jsPDF jsPDF. It is easy to use by plugin
I used Mozilla's pdf.js to solve my problem.
It renders the pdf file on html5 canvas thus it allows to print the whole html page as required.
Here is the code (credit):
<html>
<body>
<script type="text/javascript" src="https://raw.github.com/mozilla/pdf.js/gh-pages/build/pdf.js"></script>
<script type="text/javascript">
function renderPDF(url, canvasContainer, options) {
var options = options || { scale: 1 };
function renderPage(page) {
var viewport = page.getViewport(options.scale);
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var renderContext = {
canvasContext: ctx,
viewport: viewport
};
canvas.height = viewport.height;
canvas.width = viewport.width;
canvasContainer.appendChild(canvas);
page.render(renderContext);
}
function renderPages(pdfDoc) {
for(var num = 1; num <= pdfDoc.numPages; num++)
pdfDoc.getPage(num).then(renderPage);
}
PDFJS.disableWorker = true;
PDFJS.getDocument(url).then(renderPages);
}
</script>
<h3>MUST BE PRINTED</h3>
<p> MUST BE PRINTED</p>
<div id="holder"></div>
<h3>MUST BE PRINTED</h3>
<p> MUST BE PRINTED</p>
<script type="text/javascript">
renderPDF('yourFile.pdf', document.getElementById('holder'));
</script>
</body>
</html>
Here is a simpler solution using javascript.
<body>
<h3 id='first_h3'>MUST BE PRINTED</h3>
<p id ='first_paragraph'> MUST BE PRINTED</p>
<div id="pdfRenderer"></div>
<h3 id='second_h3'>MUST BE PRINTED</h3>
<p id='second_paragraph'> MUST BE PRINTED</p>
<input type="submit" value="Print All"
onclick="javascript:printPage()"
/>
</body>
<script>
pages =[] // initiate an empty list here
function printPage() {
var first_h3 = document.getElementById('first_h3');
// get the first h3 tag and
// then push its innerHTML into the list
pages.push(first_h3.innerHTML);
var first_paragraph = document.getElementById('first_paragraph');
// get the first paragraph and
// then push its innerHTML into the list
pages.push(first_paragraph.innerHTML);
var pdfRenderer = document.getElementById('pdfRenderer');
// get the pdfRenderer and
// then push its innerHTML into the list
pages.push(pdfRenderer.contentWindow.document.body.innerHTML);
var second_h3 = document.getElementById('second_h3');
// get the second h3 tag and
// then push its innerHTML into the list
pages.push(second_h3.innerHTML);
var second_paragraph = document.getElementById('second_paragraph');
// get the second paragraph and
// then push its innerHTML into the list
pages.push(second_paragraph.innerHTML);
if (pages && pages.length) {
// this if statement, just checks to ensure our list is not empty before running the code.
// here is the magic, we now set the parent window to be equal to all the concatenated innerHTML
window.content.document.body.innerHTML = pages;
// then we print this new window that contains all the different parts in the exact order we pushed them into the list.
window.print();
}
else {
// do nothing
}
}
</script>
With this solution avoid the problem of the iframe being cut off if it exceeds one page. Secondly, you get only one print dialogue box even if you have multiple iframes.

How to change an html tag with Javascript? [duplicate]

This question already has an answer here:
dynamically changing HTML tag
(1 answer)
Closed 9 years ago.
I want to display the text from a string into an HTML tag without moving to next page and display it.
<body>
<div>
<label id="lbl1">Label </label>
<button id="btn1" onclick="display()">Click </button>
<script>
function display() {
var str="Hello World";
document.write(str);
}
</script>
</div>
</body>
How do I edit the contents of the label tag?
Common …
document.getElementById('lbl1').innerHTML = str;
function display() {
var str="Hello World";
var label = document.getElementById('lbl1');
label.innerHTML = str;
}
<body>
<div>
<label id="lbl1">Label </label>
<button id="btn1" onclick="display()">Click </button>
<script>
function display() {
var str="Hello World";
var label = document.getElementById("lbl1");
label.innerText = str;
}
</script>
</div>
</body>
When you click the button, the function display() is run, and the label tag's text is changed to "Hello World".
Use document.getElementById("lbl1").innerHTML = display(); and add a return statement inside the function:
function display()
{
var str="Hello World";
return str;
}
You edit the contents in a similar manner: document.getElementById("lbl1").innerHTML = "New content...";.
You could also modify your display() function a little bit to get the desired result:
function display()
{
var str="Hello World";
var label = document.getElementById("lbl1");
label.innerHTML = str;
}
Another way:
window.onload = function()
{
var button = document.getElementById("btn1");
button.onclick = function()
{
document.getElementById("lbl1").innerHTML = "Hello World";
}
}
The last way is the most desired and it's the best to put JavaScript code inside another file and attach it via the src attribute of the script element.
Let's provide a complete example:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<label id="lbl1">Label </label>
<button id="btn1">Click </button>
</body>
</html>
Then inside the JavaScript file you just register various events:
//JavaScript
window.onload = function() //You have to ensure that everything has loaded
{
var button = document.getElementById("btn1");
button.onclick = function()
{
document.getElementById("lbl1").innerHTML = "Hello World";
}
}
It's generally considered the best way to register events in a separate JavaScript file because of performance and maintenance simplicity gains. You can read more about it here.

Categories