I wanted to make a javascript loop in html like the following:
( if (var i=0; i<10; i++) { ) //<-- JAVASCRIPT
//HTML
( } ) //<-- JAVASCRIPT
I tried using the <% JAVASCRIPT %> but it won't work for me. Does anyone know who to solve this?
Thanks in advance.
This is not how javascript works. This is something you would do with PHP.
With javascript, you run it seperately from the html. Then, you create an element within your html as a wrapper to put the javascript generated html into. Like so:
HTML
<div id="myHTMLWrapper">
</div>
<script>
var wrapper = document.getElementById("myHTMLWrapper");
var myHTML = '<span class="test">Testing out my script!</span>';
wrapper.innerHTML = myHTML
</script>
See a working example here
Sorry I skipped over the for loop by the way. Let me fix it with this update... You could do it like this, you see:
<script>
var wrapper = document.getElementById("myHTMLWrapper");
var myHTML = '';
for (var i = 0; i < 10; i++) {
myHTML += '<span class="test">Testing out my script! loop #' + (i + 1) + '</span><br/><br/>';
}
wrapper.innerHTML = myHTML
</script>
for loops are control flow and thus cannot be inserted into a static context. Try mapping it, e.g.
`<html>` + data.map(function(a) { return `<div>${a}</div>` }).join('') + `</html>`
<script>
for(var i=0; i<10; i++) {
//Code here
}
</script>
https://www.w3schools.com/js/js_if_else.asp
https://www.w3schools.com/js/js_loop_for.asp
I'd suggest you read a bit before going straight into coding
Either way your script seems deficient and I cant make out what you are trying to do with it.
Check these links if you want to append elements:
https://www.w3schools.com/jquery/html_append.asp
https://www.w3schools.com/jsref/met_node_appendchild.asp
Related
I would like to manipulate the return statement from Template.info.helpers in the way that it will display iterate like:
01...How to do this? Maybe using jquery. Maybe another solution (I treid it with iterate.split("</a></div>");), thought it´s easier if I have an array. I tried a little but there was no satisfactory result. Help please.
.js
Template.info.helpers({
info() {
var iterate ="";
for (var i = 0; i < 10; i++){
iterate += "<div class='row'>" + i + "</div>";
}
return iterate;
}
)};
.html
<template name="info">
Home
</br>
hello
<p>{{info}}</p>
<!--
Gives raw text and returns it as a string -> WORKS NOT FINE:
<div class='row'><a href=0>0</a></div><div class='row'><a href=1>1</a></div> ... and so on
-->
</template>
I have a confusing problem where a line of code in my function is running before a loop which is stated above it. In my HTML I have:
<textarea id="textBox"></textarea>
<button id="submitButton" onclick="parseData()">submit</button>
<div id="put"></div>
And my JS function is:
function parseData() {
var data = $("#textBox").val();
var tab = /\t/;
data = data.split(tab);
$("#put").html($("#put").html() + "<table>");
for (var i = 0; i < data.length; i++) {
$("#put").html($("#put").html() + "<tr>"+data[i]+"</tr>");
};
$("#put").html($("#put").html() + "</table>");
return;
};
The resulting html in $("#put") is this:
<table></table>
"SiO2 (%)Al2O3 (%)TiO2 (%)CaO2 (%)MgO2 (%) 8.21.25.31.51.8 45.32.52.60.210.5 65.23.48.70.0662.3 20.11.85.42.540.2 18.91.12.34.810.7"
I'm not sure why the final </table> is being placed before the for loop runs, and I'm not sure why the <tr> tags aren't being added within the for loop. Any pointers?
jQuery automatically closes up tags upon insertion. Try this.
function parseData() {
var data = $("#textBox").val();
var tab = /\t/;
var put_html = $("#put").html() + "<table>";
data = data.split(tab);
for (var i = 0; i < data.length; i++) {
put_html += "<tr>"+data[i]+"</tr>";
};
put_html += '</table>';
$("#put").html(put_html);
return;
};
However, I notice that you aren't using <td> elements. You might want to look into fixing that too.
Every time you are adding content into the html() property rather than building the entire content and adding it.
Since you are using jQuery you can bind the event using jQuery rather than adding that directly in the HTML
<textarea id="textBox"></textarea>
<button id="submitButton">submit</button>
<div id="put"></div>
$(function(){
$("#submitButton").click(function(){
parseData();
});
function parseData() {
var data = $("#textBox").val();
var tab = /\t/;
data = data.split(tab);
// Build your html
$("#put").html('htmlstructure');
return;
}
});
Also you can look for something similar like concatenating the string in an array so that you don't create string isntances each time when you append, since strings are immutable.
Good example
I try to build some html-code by a javascript. But somehow all html-tags I open get closed directly by the javascript. How can I change this behavior?
Example of javascript:
function generateHTML() {
var s='<table>';
for(var i=0;i<max;i++) {
s=s+'<tr><td>text</td></tr>';
}
s=s+'</table>';
document.getElementById('tagID').innerHTML = s;
}
The final html-code looks like:
<table></table>
<tr><td>text</td></tr>
:
<tr><td>text</td></tr>
</table>
Save your final writing/appending of HTML until the end of your for-loop. Output your HTML more like this:
var s = '<table>';
for(var i=0; i<max; i++) {
s += '<tr><td>text</td></tr>'; // append to s
}
s += '</table>'; // append to s
console.log(s);
Output:
<table><tr><td>text</td></tr><tr><td>text</td></tr></table>
Demo: JSBin
I am working on a website where I dont have any control on the code (functionality side. however even if I had the access I wouldn't be able to make any changes as I am a front end designer not a coder..lol). The only changes I can make is CSS, js.
What I am tring to do:
I got the url on the page like this:
www.test.com/#box1#box3#box5
(I am not sure if I can have more than one ID in a row. please advice. However thats how the developer has done it and I dont mind as there are no issues yet)
the page html
<div id="box1"></div>
<div id="box2"></div>
<div id="box3"></div>
<div id="box4"></div>
<div id="box5"></div>
I would like to take different ids from the URl and use it to hidhlight the divs with that ID (by addding a class name "highlight")
The result should be like this:
<div id="box1 highlight"></div>
<div id="box2"></div>
<div id="box3 highlight"></div>
<div id="box4"></div>
<div id="box5 highlight"></div>
I would like to learn the smart way of taking just the id numbers from the url and use it to select the div with that paticulat no.
just a quick explanation:
var GetID = (get the id from the URL)
$('#box' + GetID).addClass('highlight');
Try This...
var hashes =location.hash.split('#');
hashes.reverse().pop();
$.each(hashes , function (i, id) {
$('#'+id).addClass('highlight');
});
Working fiddle here
var ids = window.location.hash.split('#').join(',#').slice(1);
jQuery(ids).addClass('highlight');
or in plain JS:
var divs = document.querySelectorAll(ids);
[].forEach.call(divs, function(div) {
div.className = 'highlight';
});
There are various way to resolve this issue in JavaScript. Best is to use "split()" method and get an array of hash(es).
var substr = ['box1','box2']
// Plain JavaScript
for (var i = 0; i < substr.length; ++i) {
document.getElementById(substr[i]).className = "highlight"
}
//For Each
substr.forEach(function(item) {
$('#' + item).addClass('highlight')
});
//Generic loop:
for (var i = 0; i < substr.length; ++i) {
$('#' + substr[i]).addClass('highlight')
}
Fiddle - http://jsfiddle.net/ylokesh/vjk7wvxq/
Updated Fiddle with provided markup and added plain javascript solution as well -
http://jsfiddle.net/ylokesh/vjk7wvxq/1/
var x = location.hash;
var hashes = x.split('#');
for(var i=0; i< hashes.length; i++){
var GetID = hashes[i];
//with jQuery
$('#box' + GetID).addClass('highlight');
//with Javascript
document.getElementById('box' + GetID).className = document.getElementById('box' + GetID).className + ' highlight';
}
I am trying to use a for loop in html but i dont even know if this is possible. Is it? and if yes how? I dont want to use php. only html and javascript.
this is my goal: i have a file containing .txt files. i want to count the number of txt files and when i get the number i want to send it to where i will use a for loop to put the txt file's numbers in a dropbox.
Thanks
Lots of answers.... here is another approach NOT using document.write OR innerHTML OR jQuery....
HTML
<select id="foo"></select>
JS
(function() { // don't leak
var elm = document.getElementById('foo'), // get the select
df = document.createDocumentFragment(); // create a document fragment to hold the options while we create them
for (var i = 1; i <= 42; i++) { // loop, i like 42.
var option = document.createElement('option'); // create the option element
option.value = i; // set the value property
option.appendChild(document.createTextNode("option #" + i)); // set the textContent in a safe way.
df.appendChild(option); // append the option to the document fragment
}
elm.appendChild(df); // append the document fragment to the DOM. this is the better way rather than setting innerHTML a bunch of times (or even once with a long string)
}());
And here is a Fiddle to demo it.
Yes you can for example
write this code in html body tag
<select>
<script language="javascript" type="text/javascript">
for(var d=1;d<=31;d++)
{
document.write("<option>"+d+"</option>");
}
</script>
</select>
HTML
<select id="day" name="day"></select>
<script type='text/javascript'>
for(var d=1;d<=31;d++)
{
var option = "<option value='" + d + "'>" + d + "</option>"
document.getElementById('day').innerHTML += option;
}
</script>
May be you can play with javascript and innerHTML. Try this
HTML
<body onload="selectFunction()">
<select id="selectId">
</select>
Javascript
function selectFunction(){
var x=0;
for(x=0;x<5;x++){
var option = "<option value='" + x + "'>Label " + x + "</option>"
document.getElementById('selectId').innerHTML += option;
}
}
One way is to use DynamicHTML. Let the html page have a place holder for the options of select tag.
<select id="selectBox"></select>
In a js file
var options = ["one","two","three"], selectHtml = "";
for(var optionIndex = 0; optionIndex < options.length; optionIndex++) {
selectHtml += ("<option>" + options[optionIndex] + "</option>");
}
document.getElementById("selectBox").innerHTML = selectHtml;
Put the above code in a function and call that function onload.
No you can't use a for loop in HTML. HTML is a markup language, you cannot use logical code. However you could use javascript to do your logic depending on what your objective is.
Here is an example using jQuery, a popular javascript library:
for(i=0; i<5; i++){
$("select").append("<option>" + i + "</option>");
}
See example: http://jsfiddle.net/T4UXw/
HTML is not a programming language, just a markup language, so it doesn't include things like for loops or if statements. Javascript does though. You could use javascript to generate/manipulate the HTML, and thus use for loops to create your <option> tags inside the <select>. As a startup for javascript see checkout w3schools.com
I don't like using plain javascript though, I would rather choose a javascript framework like jQuery to do this. Using jquery it is really easy to do cross-platform compatible manipulation of the HTML dom using javascript. You would only need to include some extra javascript files inside your HTML to get it working.
See http://jquery.com/
An example of using jquery would be this:
<select id='myselect'></select>
<script type='text/javascript'>
var values=[[1,'tree'],[2,'flower'],[3,'car']];
for(v in values){
var option=$('<option></option>');
option.attr('value',values[v][0]);
option.text(values[v][1]);
$('#myselect').append(option);
}
</script>
You can also try this out on http://jsfiddle.net/6HUHG/3/