Using string from .js file in HTML - javascript

Hello everyone, below I have script.js and index.html. I want to use the variable outputHTML from script.js in the script tags of index.html so that I can print them in table form on my page (I'm pretty sure I have to do it this way because I'm using node). However index.html won't seem to recognize the vale of outputHTML from script.js and I have no idea why. Hopefully someone can help, thanks in advance.
script.js
var outputHTML = '';
var animals = ["cat", "dog", "goat", "turkey", "buffalo"];
// Loop over our arrays and create our html string
outputHTML += "<table>";
for (var i = 0; i < animals.length; i++) {
outputHTML += "<tr>";
outputHTML += "<td>" + animals[i] + "</td>";
outputHTML += "</tr>";
}
outputHTML += "</table>";
export { outputHTML };
------------------------------------------------=
//index.html file
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript"
src="script.js">
</script>
</head>
<body>
<button onclick= "f()">
Click To Access Animals
</button>
<div>
<p id="text" style="color:purple;
font-weight:bold;font-size:20px;">
</p>
</div>
<script type="text/javascript">
import { outputHTML } from './script.js';
function f() {
document.getElementById("text").innerHTML = outputHTML;
}
</script>
</body>
</html>

Related

Display sum of specific column in Javascript

I wish to display sum of amount for particular region.
Below is my code to display the data, however I am sure how to add up the amount.
I am able to read csv file an display in html table.
I am new to Javascript. Any help to proceed would be much appreciated
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript">
function loadFile(o)
{
var fr = new FileReader();
fr.onload = function(e)
{
showDataFile(e, o);
};
fr.readAsText(o.files[0]);
}
function showDataFile(e, o)
{
var getCSVData = e.target.result;
var rows = getCSVData.split("\n");
var html = '<table border="1">';
rows.forEach((data, index) =>
{
html += "<tr>";
var value = data.split(",");
var region = value[1];
var amount =value[3];
if(region=="SA")
{
html += "<td>" + region + "</td>";
html += "<td>" + amount + "</td>"
}
html += "</tr>";
});
html += '</table>';
document.getElementById("data").innerHTML = html;
document.getElementById("data").style.color="blue";
}
</script>
<title> Read CSV file using JavaScript </title>
</head>
<body>
Select file to read <input type="file" onchange="loadFile(this)">
<pre id="data"></pre>
</body>
</html>
You need to create a variable that you use as an accumulator to save the result of the sum, for example:
var sum = 0;
for (i = 1; i <= 10; i++) {
sum += 10;
}
console.log(sum)
Following your idea, you need to create a variable initialized at 0 before forEach and then inside the loop, accumulate its result
NOTE:
1. When you read your .csv file, it is received as a String, so the value of the variable amount is also a String, so before making the sum it should be transformed to a Number type to avoid concatenate
(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number)
Solution:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script type="text/javascript">
function loadFile(o)
{
var fr = new FileReader();
fr.onload = function(e)
{
showDataFile(e, o);
};
fr.readAsText(o.files[0]);
}
function showDataFile(e, o)
{
var getCSVData = e.target.result;
var rows = getCSVData.split("\n");
var html = '<table border="1">';
var sum = 0;
rows.forEach((data, index) =>
{
html += "<tr>";
var value = data.split(",");
var region = value[1];
var amount = value[3];
if(region=="SA")
{
if (Number(amount)) {
sum += Number(amount)
}
html += "<td>" + region + "</td>";
html += "<td>" + amount + "</td>"
}
html += "</tr>";
});
html += '</table>';
html += '<span>' + sum + '</span>';
document.getElementById("data").innerHTML = html;
document.getElementById("data").style.color="blue";
}
</script>
<title> Read CSV file using JavaScript </title>
</head>
<body>
Select file to read <input type="file" onchange="loadFile(this)">
<pre id="data"></pre>
</body>
</html>

How to write a for loop with forms in JavaScript

I'm new to JS.
I want to write a for-loop in JS that gives out a chosen number of forms.
This is what I got so far. (Maybe I have to write a function. But I have no clue how to continue.)
<!DOCTYPE html>
<html lang="de">
<head>
<title>Survey</title>
<link rel="stylesheet" type="text/css" href="survey.css">
</head>
<body>
<h1><?php echo "Title: ".$_POST["title"];
?></h1>
<script>
var Ausgabe = "";
for (var i = 1; i <= <?php echo $_POST["anzahl"];?>; i++){
Ausgabe = i + ". question: " + <form>
<input type="text" id="title" name="title">
</form>
document.write(Ausgabe)
}
</script>
</body>
</html>
Any tips are welcome.
You could do this with JavaScript:
var Ausgabe = "";
for (var i = 1; i <= <?php echo $_POST["anzahl"];?>; i++){
Ausgabe = i + ". question: " + "<form><input type=\"text\" id=\"title\" name=\"title\"></form>"
document.write(Ausgabe)
}
Adding quotes around the "html" string and escaping the quotes inside it (like type=\"text\").
Anyway I think should be better do the loop directly via PHP, something like:
<?php
for ($i = 1; $i <= anzahl; $i++) {
echo "<form><input type=\"text\" id=\"title\" name=\"title\"></form>";
}
I hope it helps, bye.
I do not know what your goals are, but I think you are trying to do something like this:
var input = prompt('Enter a number (<= 10):'),
html = '';
if (Number(input) <= 10) {
for (var i = 0; i < Number(input); i++) {
html += '<form>';
html += ' <input type="text" placeholder="' + i + '">';
html += '</form>';
}
} else {
console.log('The number is too high!');
}
document.body.innerHTML = html;

Why is this external script being loaded directly after an internal script?

Why should I link an external script write after an internal script as following example
Can anyone tell me why I should use it like this and why it doesn't display anything before the call to the external script ?
<!DOCTYPE html>
<html>
<body>
<div id="id01"></div>
<script>
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i<arr.length; i++) {
out += '<a href="' + arr[i].url + '">' +
arr[i].display + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
</script>
<script src="myTutorials.js"></script>
</body>
</html>

Why doesn't my for loop execute?

When i use document.write it works, but it doesn't work with getElementById.
The same for while.
`
<div id="mydiv"></div>
<script>
var i = 0;
for (i=0; i<=10; i++){
//while (i<=10){
document.getElementById("mydiv").innerHTML = i + "<br>";
//i++;
}
</script>
Output is just 10, but I want to list 0-10 line by line. How to fix?
Each time your loop ran, it overwrite innerHTML for the div.
This implementation starts with an empty string for html, then uses += to concatenate the counter and <br> on each iteration.
var i = 0;
var html = '';
for (i=0; i<=10; i++){
html += i + '<br>';
}
document.getElementById("mydiv").innerHTML = html;
You are over-writing or replacing the contents. You need to append, so you can use += operator instead of =.
<div id="mydiv"></div>
<script>
var i = 0;
for (i=0; i<=10; i++){
document.getElementById("mydiv").innerHTML += i + "<br>";
}
</script>
You're overwriting. Append instead.
for (var i = 0; i <= 10; i++) {
var div = document.getElementById("mydiv");
div.innerHTML = div.innerHTML + "<br/>" + i;
}
<div id="mydiv"></div>
While other answers are true, I think it's a risky practice because your browser might try to execute the code before having loaded all html elements. (For example if your div is after the code..)
So I propose this:
<div id="mydiv">
<script>
for (var i=0; i<=10; i++){
document.write ( i + "<br />");
}
</script>
</div>
N.B: However, keep in mind you cannot use "document.write" after the page finished loading.
You can also do that to be safe:
<div id="mydiv"></div>
<script>
document.onload = function(){
temp=""
for (var i=0; i<=10; i++){
temp += i + "<br />";
}
document.getElementById("mydiv").innerHTML = temp;
}
</script>

Dynamically adding script element to a div does not execute the script

I am trying to add a script block dynamically to the document. When I do this, the script block is not getting executed.
<body>
<div id="dynamicDiv">
</div>
<script type="text/javascript">
var elem = document.getElementById("dynamicDiv");
var tmpStr = "<script type=\"text\/javascript\"> ";
tmpStr += "function hello (val)";
tmpStr += "{";
tmpStr += "alert('hello ' + val);";
tmpStr += "}";
tmpStr += "<\/script>";
elem.innerHTML = tmpStr;
hello("World");
</script>
</body>
The above code does not work. From another post (How do you execute a dynamically loaded JavaScript block?), I saw a reply that if script is added to innerHTML, it will not be executed. Instead of directly using innerHTML, create a div with this innerHTML and use appendChild to add the script.
<body>
<div id="dynamicDiv">
</div>
<script type="text/javascript">
var elem = document.getElementById("dynamicDiv");
var tmpStr = "<script type=\"text\/javascript\"> ";
tmpStr += "function hello (val)";
tmpStr += "{";
tmpStr += "alert('hello ' + val);";
tmpStr += "}";
tmpStr += "<\/script>";
var newdiv = document.createElement('div');
newdiv.innerHTML = tmpStr;
elem.appendChild(newdiv);
hello("World");
</script>
</body>
How ever, this solution also did not work for me.
In another reply, I again saw that we should get the script elements and execute them using eval.
<body>
<div id="dynamicDiv">
</div>
<script type="text/javascript">
var elem = document.getElementById("dynamicDiv");
var tmpStr = "<script type=\"text\/javascript\"> ";
tmpStr += "function hello (val)";
tmpStr += "{";
tmpStr += "alert('hello ' + val);";
tmpStr += "}";
tmpStr += "<\/script>";
var newdiv = document.createElement('div');
newdiv.innerHTML = tmpStr;
elem.appendChild(newdiv);
var scripts = newdiv.getElementsByTagName('script');
for (var ix = 0; ix < scripts.length; ix++) {
eval(scripts[ix].text);
}
hello("World");
</script>
</body>
This solution works for me.
But if do this in a function then it does not work.
<body>
<div id="dynamicDiv">
</div>
<script type="text/javascript">
function createFunction(){
var elem = document.getElementById("dynamicDiv");
var tmpStr = "<script type=\"text\/javascript\"> ";
tmpStr += "function hello (val)";
tmpStr += "{";
tmpStr += "alert('hello ' + val);";
tmpStr += "}";
tmpStr += "<\/script>";
var newdiv = document.createElement('div');
newdiv.innerHTML = tmpStr;
elem.appendChild(newdiv);
var scripts = newdiv.getElementsByTagName('script');
for (var ix = 0; ix < scripts.length; ix++) {
eval(scripts[ix].text);
}
hello("World 1");
}
createFunction();
hello("World 2");
</script>
</body>
I can see that the function is available after the script is evaled. and is available in the function createFunction. Outside createFunction() scope, hello() is not available.
What am I doing wrong? Am I missing something very basic? Please check and help.
Thanks,
Paul
P.S. I don't use jQuery.
I am using chrome to test this.
Would like to point out that the reason the 3rd snippet you provided works inside the for loop, but not outside is because you are using eval. eval takes a string and executes it as js, which is why it is working inside the loop, but using eval isn't parsing it for future use, which is causing it to be unusable elsewhere. Therefore, when you go to call it outside the loop, you get a reference error.
UPDATE:
If you are getting the string back with the <script> tags in it, you can just parse out the script tags.
var string = "<script type=\"text\/javascript\"> ";
string += "function hello (val)";
string += "{";
string += "alert('hello ' + val);";
string += "}";
string += "<\/script>";
string = string.replace(/<(script|\/script).*?>/g,'');
function createFunction() {
var elem = document.getElementById("dynamicDiv");
var script = document.createElement('script');
script.innerHTML = string;
elem.appendChild(script);
hello("World 1");
}
createFunction()
hello('world 2');
JSFiddle: http://jsfiddle.net/3wYD6/
I don't really see the point of this, but if you really want to do this you can create a new script element and then set it's innerHTML to the function, then append the new script to a div.
var elem = document.getElementById("dynamicDiv"),
script = document.createElement('script');
script.innerHTML =
'function hello (val) {' +
'alert("hello " + val);' +
'}';
elem.appendChild(script);
hello('world');
In your first try you are creating a string and js interpreter handle it as a string, not an html tag, so js doesn't really care about your script tags presented in that string.
Then of course it's working when you start using eval() because eval - is evil:))
After all you can create script tags dynamically and then fill it with code:
var elem = document.getElementById("dynamicDiv"),
scriptTag = document.createElement('script'),
scriptTagCode = 'function hello (val){alert("hello " + val);}';
scriptTag.innerHTML = scriptTagCode;
elem.appendChild(scriptTag);
hello('foo');

Categories

Resources