write html in javascript without documet.write - javascript

<script >
for(i=0;i<=9;i++)
{
</script>
<input type="button" value="1"/>
<script type="text/javascript">
}
</script>
This puts button only 1 time if I use document.write it prints 10 times why ?

JavaScript does not behave in the same way PHP does. Whatever you place between the <script> tags is a script in and of itself.
So you have two separate scripts:
This:
for(i=0;i<=9;i++)
{
and this one:
}
Imagine what would happen if you placed these two scripts into two separate files? That's right, both would fail because of syntax errors. If you take a look at the console you'll see what errors I'm talking about.
If you want to print 10 buttons do something like this:
<div id="mainDiv">
</div>
<script>
var mainDiv = document.getElementById('mainDiv');
for(var i=0; i<10; i++){
mainDiv.innerHtml += "<input type='button' value='1'>";
}
</script>

These script tags are separate scripts. You can use functions or variables defined in the first one, but you cannot have a for loop spanning both.
The html in between is not in the script either. It looks like your trying to use script tags as if they're <?php?> ones.
Alternatives to document.write, is setting the contents of an element's innerHTML or adding an element to the DOM:
for(i=1;i<10;i++){
var btn = document.createElement("button");
document.body.appendChild(btn);
}

HTML is not a template engine as PHP so you can't separate a code block into multiple script tags. Each code block must be placed entirely in a <script></script> tag pair.
If your purpose is generate 10 buttons with Javascript, please go with document.write option

you are looking for some sort of server side templating. remember javascript runs on the client.

Related

Passing HTML value to embedded script

So I have a HTML file with an embedded script. A Java application sends a value to this HTML file. Now I wonder how to pass this value from the HTML down to the script. Is this even possible?
Here is the simplified HTML file with my approach:
<html>
<body>
<div id="test">
[VALUE_FROM_BACKEND] // prints "let valueFromBackend = 1234"
</div>
<script>
console.log(document.getElementById('test').value);
// should return: let valueFromBackend = 1234;
// actually returns: undefined
</script>
</body>
</html>
Unfortunately, I can't pass the value from the Java application directly to the script. I got the above approach from here, but this doesn't work.
Other solutions only focus on getting values from remote HTML pages, declaring the HTML files's source in the script tag. But since it is an embedded script here, this also seems not to work.
Does anyone know how to deal with the situation? Help will be much appreciated.
Only HTML input elements have a value in javascript. A div cannot have a value, which is why your code returns undefined.
To access the text inside a regular HTML element, such as a div, use element.innerText instead.
Here is a working code snippet you can try out:
console.log(document.getElementById('test').innerText);
<div id="test">
let valueFromBackend = 1234
</div>
As you want to get value of a div element, so the syntax is:
document.getElementById('test').innerHTML
Remember that getElementById().value works for input and use getElementById().innerHTML for elements like div

Difficulty with using HTML DOM .createElement(), .setAttributeNode(), and .appendChild() methods

I'm learning how to develop a dynamic webpage and am trying to use HTML DOM to add JS objects but nothing is appearing after several troubleshooting attempts.
I've tried using .createAttribute() instead of .setAttribute() and have carefully read the descriptions of all the methods to make sure I was using them correctly.
<html>
<body>
<div id="greeting_section">
</div>
<script>
let greeting_post = document.createElement("P");
greeting_post = document.setAttributeNode("id","post");
let greeting_post_text = document.createTextNode("howdy howdy");
greeting_post.appendChild(greeting_post_text);
document.getElementById("greeting_section").appendChild(greeting_post);
</script>
</body>
</html>
I expect it to output "howdy howdy" but nothing appears in my Firefox browser.
It looks like you're overwriting greeting_post. Also, you might just be meaning to use setAttribute instead of setAttributeNode. See below for a working example.
let greeting_post = document.createElement("P");
greeting_post.setAttribute("id","post");
let greeting_post_text = document.createTextNode("howdy howdy");
greeting_post.appendChild(greeting_post_text);
document.getElementById("greeting_section").appendChild(greeting_post);
<html>
<body>
<div id="greeting_section">
</div>
</body>
</html>
First: When I ran your code the browser console showed this error
Uncaught TypeError: document.setAttributeNode is not a function
That's the first thing you should do when your code doesn't work, Take a look at the browser console.
Second: in your code greeting_post = document.setAttributeNode("id","post"); you are trying to add id="post" to greeting_post variable which is the p tag put you do it wrong, Your code means change the variable greeting_post to a new value document.setAttributeNode("id","post"); which mean Set attribute id="post" to the document.
So, instead of your code, The correct code should go like this:
greeting_post.setAttribute("id","post");
In English this is mean, select greeting_post and set it's attribute to id="post"
So finale, The complete code should be like this:
let greeting_post = document.createElement("P"),
greeting_post_text = document.createTextNode("howdy howdy");
greeting_post.setAttribute("id","post");
greeting_post.appendChild(greeting_post_text);
document.getElementById("greeting_section").appendChild(greeting_post);

Smarty - can't insert variable content into javascript

I need to insert content of variable with Smarty syntax into javascript, like below. The script is checking if page is opened from validation link in email sent to customer.
{literal}
<script>
if ((document.URL).indexOf("validation") > -1) {
$('.loginForm').append(
"<p class='middleWarningTextP loginMessage'>{/literal}{$VALIDATION_NOTICE->getMessage()}{literal}</p>");
}
</script>
{/literal}
Problem is, that this works only if javascript condition is true, otherwise page is loaded wrong: between <header> and </header> tag is nothing! and therefore css style is not loaded. I don't understand it, is there a way to repair it?
You should remove the {literal} tags. Smarty does not execute statements within these tags More info. But then, if use curly braces inside your javascript, you need to write your statements on multiple lines:
var test = {
value: 'test'
}
If you're using Smarty 3
<script>
if ((document.URL).indexOf("validation") > -1) {
$('.loginForm').append(
"<p class='middleWarningTextP loginMessage'>{$VALIDATION_NOTICE->getMessage()}{literal}</p>");
}
</script>
That is, simply remove the {literal} tags
If you're using Smarty 2 instead, i think it's something like this
<script>
if ((document.URL).indexOf("validation") > -1) {ldelim}
$('.loginForm').append(
"<p class='middleWarningTextP loginMessage'>{$VALIDATION_NOTICE->getMessage()}</p>");
{rdelim}
</script>
Problem was not with {literals} tags or syntax. Problem was that $VALIDATION_NOTICE->getMessage() variable was not set in some cases. Therefore I added this condition:
{if !is_array($VALIDATION_NOTICE) and $VALIDATION_NOTICE}{$VALIDATION_NOTICE->getMessage()}{/if}
and now it works right.

Javascript - include another script by using the <script> tag?

So I have a function that writes a string into a div.
The string is declared as content, which consists of html code, like this:
<h2>This is a test result</h2>
<script type="text/javascript" src="example_content.js"></script>
<script type="text/javascript"> document.write(example_content); </script>
where example_content.js :
example_content = '<p>some text some text some text some text some text</p>'
+ '<p>some more text....</p>'
+ '<hr />'
+ '<p>End of text</p>';
Problem is, instead of getting this in the div:
<h2>This is a test result</h2>
<p>some text some text some text some text some text</p>
<p>some more text....</p>
<hr />
<p>End of Text</p>
I end up, literaly, with this:
<h2>This is a test result/h2>
<script type="text/javascript" src="example_content.js"></script>
<script type="text/javascript"> document.write(example_content); </script>
Is there a way to avoid writting the script tag as a string ? but as an actual script ?
Thanks for any help in advance :)
You can't do that. You can't add script tags and execute them by writing the HTML. If you must load scripts dynamically, you should add them to the DOM. You can try this to load an external script file and execute the method.
(function(document){
var s = document.createElement('script');
s.id = "external_content";
s.async = true;
s.src = "example_content.js";
document.getElementsByTagName('head')[0].appendChild(s);
s.onload = function() {
document.write(example_content);
}
}(document));
What it basically does is that it creates a new script element dynamically and adds it to the DOM. It also sets an onload event handler which would fire once the script is downloaded completely.
I'm not sure about this question due to the wording however you don't need two <script> tags. At the end of the example_content.js place the document.write(example_content); then remove the <script type="text/javascript"> document.write(example_content); </script> from the html file.
Also if this is what you want I would recommend you use object.innerHTML rather than document.write and place the script at the bottom of your page.
if this doesn't work or isn't what you want please put a comment and I'll remove and use JSLint for an example.
Here's some info: https://developer.mozilla.org/en-US/docs/DOM/element.innerHTML
Okay so basically you want to write HTML inside the contents of your div. Say you have a div with the following id: myContentDiv
/**
* NOTICE HOW IM USING \ before " TO ESCAPE THE CHARACTERS INSIDE THE HTML STRING
*/
var yourCustomHTMLString = "<h1>this is a tag</h1><div class=\"yourClass\">something</div>";
var contentDiv = document.getElementById('myContentDiv');
contentDiv.innerHTML = yourCustomHTMLString;
Also, in your mark-up you need to specify a trigger for your JS, for instance an onload trigger.
window.onload = function(){
document.write(example_content);
}
And now say you want a function that will load an HTML string into a div.
function loadContent(HTMLstring, targetDivID)
{
var myDiv = document.getElementById(targetDivID);
myDiv.innerHTML = HTMLstring;
}
If you are trying to include a JS script inside another JS script, you need Ajax. If you are using a JS library, all common ones have a script load method predefined.
Dynamically load a JavaScript file
If I understand you correctly, you insert your content as innerHTML into a <div> , and the scripts don't execute.
As far as I know, this is the expected behavior, as there is no onLoad, document.ready etc. event when you alter the innerHTML of an element.
You could parse the inserted string for <script> nodes. Warning, this is a very "hacky" thing to do, usually there are better ways, for example using the success callback of the ajax functions of the various script libraries.
Nevertheless, here is what we used once. This needs to be executed after you inserted your content string. Please don't judge me, I was young and the time was short...
var div = document.getElementById("yourParentDiv");
if(div != null){
var x = div.getElementsByTagName("script");
for(var i=0;i<x.length;i++) {
eval(x[i].text);
}
}

Javascript inline output

In javascript suppose you have this piece of code:
<div>
<script type="text/javascript">var output = 'abcdefg';</script>
</div>
Is there any way to simply "echo" (using PHP terminology) the contents of output into #test? That is, to output a string inline, assuming you have no standard way of traversing or selecting from the DOM?
document.write("..."); does write the contents of output, but in doing so, it replaces the entire document with the output.
The solution I'm looking for should act the same way a PHP echo would: write the output into the document inline.
You'd have to use document.write [docs]:
<div id="test">
<script type="text/javascript">document.write('abcdefg');</script>
</div>
DEMO
With the caveat that it does not work in XHTML documents. See the documentation for more details.
"Kosher" code aside, yes.
document.write()
In standards-based browsers:
document.getElementByID("test").textContent = output;
For broader support, you could use text in jQuery (or the equivalent method if your library of choice):
$('#test').text(output);
If your code is in the div, then document.write('abcdefg') is the proper choice for inserting something inline at the point of execution.
Or, if your code is not inside the div, you can do this:
<div id="test">
</div>
<script type="text/javascript">
var output = 'abcdefg';
document.getElementById("test").innerHTML = output;
</script>
You will have to make sure that your code runs AFTER the page is loaded and the div is present.
You could write something like:
<div id="test">
<script>
document.getElementById('test').innerHTML = "stuff";
//this line only changes content in the div with id="test", not the whole dom
</script>
</div>
But you should avoid putting a script inside a div because it may be overwritten.
I know this is an old question but if anybody is still looking then here is a handy function that does the job.
function echo(text)
{
document.body.appendChild(document.createElement("div")).appendChild(document.createTextNode(text));
}
console.log()
http://getfirebug.com/logging
also supported in chrome and ie 9.. watch out for backwards compatibly it will get you ie8 and down i think...

Categories

Resources