writing text into the div using document.write - javascript

I am trying to add text to two DIVS with ids= DIV1 and DIV2 in a html page(home.html) from a js page main.js using document.write() command. On clicking the button in html page, the respective text must appear in the hmtl page.
The code is as given below. I keep getting an error: document.write can be a form of eval. Is there a possible way of using document.write() and print the text in the div sections.
HTML code:
<head>
<script src="main.js" type="text/javascript"></script>
</head>
<body>
<form>
<input type="button" value="click!" onclick="xyz()">
</form>
</body>
JAVASCRIPT code:
function xyz(){
var arr={name:"abc",school:"pqrst"};
document.write('<div id="div1">'+"Name:"+ arr.name +'</div>');
document.write('<div id="div2">'+"School:"+ arr.school +'</div>');
}
Name:abc
School:pqrst

...using document.write() command
Don't. Only use document.write during the initial parsing of the page, or to write to a new window you've just opened (or better yet, don't use it at all).
Instead, use the DOM. Example:
function xyz(){
var arr = {name: "abc", school: "pqrst"};
addDiv("name", "Name:" + arr.name);
addDiv("age", "School:" + arr.school);
}
function addDiv(id, content) {
var d = document.createElement("div");
d.id = id;
d.textContent = content;
document.body.appendChild(d);
}
<input type="button" value="click!" onclick="xyz()">
If you have an HTML string you want to insert, you can do that with insertAdjacentHTML, but beware of combining text from an object with HTML, because any < or & in the text must be escaped correctly (more than that if you're going to put the content into an attribute, as with your id values). It happens that your two example values don't have those characters, but you can't assume that in the general case.

You can use insertAdjacentHTML() in place of document.write(). Refer this for more details
function xyz(){
var arr={name:"abc",school:"pqrst"};
document.querySelector('body').insertAdjacentHTML('beforeend','<div id="name">'+"Name:"+ arr.name +'</div>');
document.querySelector('body').insertAdjacentHTML('beforeend','<div id="age">'+"School:"+ arr.school +'</div>');
}
<body>
<form>
<input type="button" value="click!" onclick="xyz()">
</form>

Related

Call javascript function from html in different locations

I'm trying to call a javascript function that allow to print a div, defined as:
function printdiv(printpage) {
var headstr = "<html><head><title></title></head><body>";
var footstr = "</body>";
var newstr = document.all.item(printpage).innerHTML;
var oldstr = document.body.innerHTML;
document.body.innerHTML = headstr+newstr+footstr;
window.print();
document.body.innerHTML = oldstr;
return false;
}
That is inside a file 'main.js' in a js folder. The HTML file has a button that calls this function:
<input id="downloadScan" type="button" onclick="printDiv('document');" class="btn btn-default" value="Print">
And the same html file contains the location of the javascript function:
<script src="./js/main.js"></script>
But when I click the button, nothing happens. I tried to directly put the function inside the HTML file and it works. What is the problem?
Normally you would place script tags in your page header (or in some cases body) however given they are not present at page load I fear it may be an execution order problem.
It appears as though you are trying to dynamically create pages, you can achieve this with out needing to create the entire structure of the page, and instead just dynamically creating the content (body). It also appears as though you are trying to maintain the contents of the body and do an "append".
Try the following setup:
index.html
<html>
<head>
<script src="./js/main.js"></script>
</head>
<body>
<input id="downloadScan" type="button" onclick="appendDiv('Some text not in a div');" class="btn btn-default" value="Print">
<input id="downloadScan2" type="button" onclick="appendDiv('<div>Some content in a div</div>');" class="btn btn-default" value="Print">
</body>
</html>
main.js
function appendDiv(content) {
document.body.innerHTML = document.body.innerHTML + content;
}
https://jsfiddle.net/acvgout7/

issue with using innerHTML() and inserting javascript variable values into HTML

I am working on a small word counter for a school assessment and can't see what is wrong with this code. The idea is when you hit the submit button, it displays "Word Count: " and the amount of character put into a text box. I have showed the teacher my code and he agrees that he doesn't see a problem with it.
Javascript:
window.onload = function(){
var input = document.getElementById(userInput).value;
if(submit.onclick) {
document.getElementById("wordCount").innerHTML = "Word Count: " + input.length;
};
};
HTML:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type='text/javascript' src='script.js'></script>
</head>
<body>
<h1 style='font-family:verdana;text-decoration:underline;'>Word Counter</h1>
<p>Please input text into the text box below:</p>
<input type='text' id='userInput'/>
<button id='submit'>Submit</button>
<p id='wordCount'></p>
<script type='text/javascript' src='script.js'></script>
</body>
</html>
document.querySelector('#submit').addEventListener('click', function(e) {
const input = document.querySelector('#userInput');
const inputValue = input.value;
const wordsArray = inputValue.split(' ');
document.querySelector('#wordCount').innerText = `Word Count: ${wordsArray.length}`;
})
<h1 style='font-family:verdana;text-decoration:underline;'>Word Counter</h1>
<p>Please input text into the text box below:</p>
<input type='text' id='userInput'/>
<button id='submit'>Submit</button>
<p id='wordCount'></p>
First on window load there is likely no information inside the #userInput, meaning
var input = document.getElementById(userInput).value; will be undefined or ''.
Second, you have no click event bound to your submit button so
submit.onclick will return false;
Binding DOM events
Lastly I switched from using .innerHTML to .innerText as there is no HTML being added into it. Also you your original code was not getting the word count, but would have returned the character count of the input text. To get word count I split the input text on spaces and returned the length of that array as the word count.
Try putting quotes around your userInput inside your getElementById. Right now you're trying to get an element by an ID of undefined because the userInput variable doesn't exist.

document.getElementById doesn't get newly entered HTML text input value

I use the following code.
The idea is to print the contents of the div with name "PrintThis" which incorporates the text input area "textarea1".
The problem is that getElementById only ever returns the string loaded with the page; "cake" in this case.
If I change "cake" to "pie" by clicking and typing into "textarea1" on the page then printContents still has "cake" not "pie".
<html>
<head> </head>
<script type="text/javascript">
function printFunction(divName) {
var printContents = document.getElementById(divName).innerHTML;
//Now call a script to print (not included)
}
</script>
<body>
<div id="printThis" name="printThis">
<textarea id="textarea1" cols="1" rows="10" style="width:95%!important;" ">cake</textarea>
</div>
<input type="button" value="Print Div" onClick="printFunction('printThis')">
</body></html>
In my production version I also use AJAX to post the text area value back to the server, so could in theory use a page refresh, though that doesn't run, I tried using these options.
document.location.reload(true);
window.top.location=window.top.location;
The production version does have jQuery available too.
first of all you are trying to get innerHTML of the div, instead of the actual textarea.
secondly instead of trying to get innerHTML try using value.
http://jsfiddle.net/qdymvjz8/
<div id="printThis" name="printThis">
<textarea id="textarea1" cols="1" rows="10">cake</textarea>
</div>
<input type="button" value="PrintDiv" onClick="printFunction('textarea1')">
function printFunction(divName) {
var printContents = document.getElementById(divName).value;
}
If you are having multiple items in your div in production then you can iterate through the children of the div and drag out the values.
function printFunction(divName) {
var printContents = document.getElementById(divName),
childItemCount = 0,
stringToPrint = '';
for (childItemCount; childItemCount < printContents.children.length; childItemCount++) {
stringToPrint += printContents.children[childItemCount].value;
}
console.log(stringToPrint);
//Now call a script to print (not included)
}

Javascript appendChild(script) works only one time

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().

Using the GetElementByClassName and GetElementById

I want to print variables in the same paragraph but on different lines. I was using this:
<p id="demo1"></p><p id="demo2"></p><p id="demo3"></p>
<button type="button" onclick="myFunction()">Try It!</button>
<script>
function myFunction()
{
var lastname="Doe";
var age=30;
var job="carpenter";
document.getElementById("demo1").innerHTML=lastname;
document.getElementById("demo2").innerHTML=age;
document.getElementById("demo3").innerHTML=job;
}
</script>
but it prints each value in a new paragraph. I tried changing to classname instead but I'm doing something wrong. Help me please. TY.
<p class="demo1, demo2, demo3"></p>
<button type="button" onclick="myFunction()">Try It!</button>
<script>
function myFunction()
{
var lastname="Doe";
var age=30;
var job="carpenter";
document.getElementByClassName("demo1").innerHTML=lastname;
document.getElementByClassName("demo2").innerHTML=age;
document.getElementByClassName("demo3").innerHTML=job;
}
</script>
Also can you use
document.getElementById("demo1").innerHTML=lastname;
and more then one id and value at then end? Something like this?
document.getElementById("demo1,demo2,demo3").innerHTML=lastname,age,job;
How can you read that correctly, I know the above not valid, but what is the correct method to do it?
Ty
Jared Moore
<p id="demo1"></p>
<button type="button" onclick="myFunction()">Try It!</button>
<script>
function myFunction()
{
var lastname="Doe";
var age=30;
var job="carpenter";
var concat = lastname + '<br />' + age + '<br />' + job
document.getElementById("demo1").innerHTML=concat;
}
</script>
The reason that the three parts are in three different paragraphs is that you have three p elements. If you want all the values to be in the same paragraph, you should use an inline element, such as span. This is what it would look like:
<p><span id="demo1"></span><span id="demo2"></span><span id="demo3"></span></p>
By the way, using innerHTML is asking for someone to hack your site; if your real code looks anything like this:
element.innerHTML = userSuppliedData
then anyone can run whatever JavaScript they want on your page by passing this:
<script type="text/javascript">
alert('All your site are belong to us.');
</script>
This is known as cross-site scripting, XSS. Instead, do this:
element.appendChild(document.createTextNode(userSuppliedData))

Categories

Resources