How to create a JavaScript loop to display an output 100 times - javascript

I’m doing an exercise for high school. The exercise is to create an input and the input needs to be displayed 100 times ( 1) input 2) input 3) input, etc..) and you are not allowed to do it manually; you need to create a loop.
This is what I have so far. I tried googling it for an hour, but I didn't find anything.
<!DOCTYPE HTML>
<html>
<head>
<title>JS example</title>
<style>
body{font-size: 130%; background-color: teal; color: yellow}
input, button {font-size: 90%;}
#output {font-weight: bold; color: blue}
</style>
<script>
function getText(id){
var text = document.getElementById(id).value;
return text;
}
function showReply(id, reply){
document.getElementById(id).innerHTML = reply;
}
function reply(){
var textFromUser = getText("myTextField");
var str = something;
showReply("output", reply);
}
var something = [
[var text = "";]
[var i;]
[for (i = 0; i < 5; i++) {]
[reply += i + ")" + textFromUser;}]
]
</script>
</head>
<body>
<h1>What does a function say?</h1>
<p>Write some text in the text field and press the button.</p>
<input type="text" id="myTextField">
<button onclick="reply()">click?</button>
<p> Reply: <span id="output"></span> </p>
</body>
</html>
How can I do it?

You can create an element and append to your output container using a for loop. Try this:
function getText(id){
var text = document.getElementById(id).value;
return text;
}
function showReply(id, reply){
let container = document.getElementById(id);
let p = document.createElement('p');
p.textContent = reply;
container.appendChild(p);
}
function reply(){
var textFromUser = getText("myTextField");
for(let i = 0; i < 100; i++){
showReply("output", textFromUser);
}
}
<h1>What does a function say?</h1>
<p>Write some text in the text field and press the button.</p>
<input type="text" id="myTextField">
<button onclick="reply()">click?</button>
<p> Reply: <div id="output"></div> </p>

Variable i is used as a counter. If you want to change how many times it loops, just change the i<=num.
for (var i=1; i<=100; i++){
show_reply();
}
I suggest you to check this post on W3Schools.

I've made two files, one for HTML and the other for JavaScript.
Here is the JavaScript code:
function getText(id) {
let text = document.getElementById(id).value;
return text;
}
function showReply(id, reply) {
document.getElementById(id).innerHTML = reply;
}
function reply() {
let textFromUser = getText("myTextField");
let i;
let span1 = document.getElementById("output")
let usert = ""
for (i = 0; i < 100; i++) {
usert += "<br>" + textFromUser
}
span1.innerHTML = usert
}
Here is the HTML:
<!DOCTYPE HTML>
<html>
<head>
<title>JS example</title>
<style>
body{font-size: 130%; background-color: teal; color: yellow}
input, button {font-size: 90%;}
#output {font-weight: bold; color: blue}
</style>
<script src="main.js"></script>
</head>
<body>
<h1>What does a function say?</h1>
<p>Write some text in the text field and press the button.</p>
<input type="text" id="myTextField">
<button onclick="reply()">click?</button>
<p> Reply: <span id="output">dd</span> </p>
</body>
</html>

There are many different potential solutions for this type of question. Choose the flavor you like and put your own spin on it.
function showReply(id, reply){
document.getElementById(id).innerHTML = reply.join('<br>');
}
function reply(){
var textFromUser = getText('myTextField');
var outputs = [];
for (let i = 0; i < 100; i++){
outputs.push(`#${ i } ${ textFromUser }`)
}
showReply('output', outputs);
}

Related

Problems with javascript html dom

let tasks = []
function addV() {
let x = document.getElementById("bara")
tasks.push(x.value)
document.getElementById("t").textContent = " "
for (let i = 0; i < tasks.length; i++) {
const p = document.createElement("p");
p.innerText += tasks[i]
document.body.append(p)
console.log(tasks)
}
}
<!DOCTYPE html>
<html>
<head>
<title>To Do</title>
</head>
<body>
<script src="motor.js"></script>
<p>Task</p>
<input type="search" placeholder="task" id="bara">
<button onclick="addV()">ADD</button>
<hr>
<h1>TO DO TASKS</h1>
<p id="t"></p>
</body>
</html>
Basically i have this problem when i hit my add button second time it add again the first element from the array butt how do i manage to show only the last element without the first one in the next p elements when i hit add button
If you need list of p
let tasks = []
function addV() {
let x = document.getElementById("bara")
tasks.push(x.value)
const instance = document.getElementById("t")
instance.innerHTML = '';
for (let i = 0; i < tasks.length; i++) {
const p = document.createElement("p");
p.innerText += tasks[i];
instance.appendChild(p);
}
}
If I understand your need correctly, you do not want to "repeat" displaying "task" entered previously (which will result in displaying previous input tasks multiple times) when you perform entering new task(s).
In that case, please clear the element "t" before you update it.
So the HTML is
<!DOCTYPE html>
<html>
<head>
<title>To Do</title>
</head>
<body>
<script src="motor.js"></script>
<p>Task</p>
<input type="search" placeholder="enter the task" id="bara">
<button onclick="addV()">ADD</button>
<hr>
<h1>TO DO TASKS</h1>
<div id="t"></div>
</body>
</html>
and the JS (motor.js) is
let tasks = []
function addV(){
if (document.getElementById("bara").value !=""){
let x = document.getElementById("bara")
tasks.push(x.value)
document.getElementById("t").textContent = " "
var tempstring=""
for(let i = 0;i<tasks.length;i++){
tempstring=tempstring +"<br>"+ tasks[i];
//const p = document.createElement("p");
// p.innerText += tasks[i]
// document.body.append(p)
}
document.getElementById("t").innerHTML=tempstring;
document.getElementById("bara").value="";
}
}
Your DOM p tag was inside the loop thus out of scope. I also created a new taskArray to hold the new tasks. This can be seen in the console log and the innerHTML is now displaying each new task just the one time.
let tasks = []
function addV() {
let x = document.getElementById("bara")
tasks.push(x.value)
document.getElementById("t").textContent = " "
let taskArray = [];
const p = document.createElement("p");
for (let i = 0; i < tasks.length; i++) {
p.innerText = tasks[i]
document.body.append(p)
taskArray.push(tasks[i]);
}
console.log(taskArray);
}
<!DOCTYPE html>
<html>
<head>
<title>To Do</title>
</head>
<body>
<script src="motor.js"></script>
<p>Task</p>
<input type="search" placeholder="task" id="bara">
<button onclick="addV()">ADD</button>
<hr>
<h1>TO DO TASKS</h1>
<p id="t"></p>
</body>
</html>

How do I activate a function with a second <button> to call a forEach?

let words = [];
var longestCt = 0;
var longestWord = "";
var myList = [];
var myList = ['Loops','are','used','while','Learning JavaScript'];
function addWords() {
let template = words.map(word => `<li>${word}</li>`).join('\n');
document.querySelector('ul').innerHTML = template;
}
addWords();
let btnAdd = document.querySelector('button');
let input = document.querySelector('input');
btnAdd.addEventListener('click', () => {
words.push(input.value);
input.value = '';
addWords();
});
let findLong = document.querySelector('button');
findLong.addEventListener('click', () => {
let longestCt = 0;
let longestWord = "";
words.forEach(function (value) {
if (value.length > longestCt) {
longestWord = value;
longestCt = value.length;
} else {
longestWord = longestWord;
}
});
//}
});
document.getElementById("demo2").innerHTML = longestWord;
div {
widows: 20%;
margin: auto;
}
input, button {
padding: 5px;
display: inline-block;
}
li {
font-size: 20px;
font-weight: bold;
margin-left: -40px;
list-style: none;
}
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="test_Arr_Input.css">
<title>Test Longest Array.html</title>
</head>
<body>
<!--Thank you to YouTube KodeBase with my modifications adding a second button which isn't working-->
<div>
<input type="text">
<button>Add a Word</button>
<ul></ul>
<br>
<button>Find the Longest</button>
<p id="demo"></p>
</div>
<script type="text/javascript" src="test_Arr_Input.js"></script>
</body>
</html>
Full disclosure; Beginner. With that said; thank you in advance.
I have written a simple JavaScript to return the longest string in an array.
Here it is as simply a JavaScript function, that I ran from the console, without interacting with the html:
var myList = ['Loops','are','used','while','Learning JavaScript'];
var longestCt = 0;
var longestWord = "";
myList.forEach(function (value) {
if (value.length > longestCt) {
longestWord = value; longestCt = value.length;
} else {
longestWord = longestWord;
}
});
console.log(longestWord);
I then endeavored to create an HTML page to enter objects into the array and to create a list.
(Thanks to KodeBase from Youtube for the direction). The JavaScript for this is posted at the end after the CSS. Here is the HTML:
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="test_Arr_Input.css">
<title>Test Longest Array.html</title>
</head>
<body>
<!--Thank you to YouTube KodeBase with my modifications adding a second button which isn't working-->
<div>
<input type="text">
<button>Add a Word</button>
<ul></ul>
<br>
<button>Find the Longest</button>
<p id="demo"></p>
</div>
<button onclick="intoMyList()">Submit to the array</button>
<p id="demo"></p>
<button onclick="findTheLongest()">Find the Longest Word</button>
<p id="demo2"></p>
<script type="text/javascript" src="test_Arr_Input.js"></script>
</body>
</html>
Here is the CSS:
div {
widows: 20%;
margin: auto;
}
input, button {
padding: 5px;
display: inline-block;
}
li {
font-size: 20px;
font-weight: bold;
margin-left: -40px;
list-style: none;
}
And here is the final JavaScript:
let words = [];
function addWords() {
let template = words.map(word => `<li>${word}</li>`).join('\n');
document.querySelector('ul').innerHTML = template;
}
addWords();
let btnAdd = document.querySelector('button');
let input = document.querySelector('input');
btnAdd.addEventListener('click', () => {
words.push(input.value);
input.value = '';
addWords();
});
let findLong = document.querySelector('button');
findLong.addEventListener('click', () => {
//function findTheLongest() {
let longestCt = 0;
let longestWord = "";
myList.forEach(function (value) {
if (value.length > longestCt) {
longestWord = value;
longestCt = value.length;
} else {
longestWord = longestWord;
}
});
//}
});
document.getElementById("demo2").innerHTML = longestWord;
First I changed a few variable names for more clarity.
But the issue is, although I am able to get the words to enter the array by clicking the first button, the second button does not seem to call the ForEach function to trigger the return of the longest word. I am wondering if I need to somehow differentiate between button 1 and 2 in the HTML. Or if I just need to go back to the drawing board to rethink my understanding of the way I am putting the JS together.
In short, you need to give each of your buttons a unique ID and then you can use this Id to target the appropriate button in your code.
<button id="add-word">Add a Word</button>
and
let btnAdd = document.querySelector('#add-word');
As mentioned by Jamiec you should give each button its own unique id and use getElementById to target it specifically with that or you can use onclick="function()" in the html to call a function from that element directly
The current point of failure also seems to be line 27 reads myList.forEach when it should be words.ForEach. I've changed a few lines and got a working example here for you: https://jsfiddle.net/z7dsabLc/6/

How to type text in HTML

I'm looking to get the HTML page to type out some text when you visit said page, as if someone behind the screen was using a keyboard even though no one is. I understand this may require the use of the <script> tag.
What I have so far
<html>
<head>
<title>Happy Valentine</title>
<style type="text/css">>
body {
background: black url("http://www.robodesign.ro/files/gallery/original/love_bites.jpg");
background-repeat: repeat;
background-position: center;
background-attachment: fixed;
}
</style>
</head>
<body onload=writetext() onLoad="setTimeout('delayer()', 2000)">
<p align=center></p>
<script language=JavaScript>
msg = new Array(); //strings written in screen
msg[0] = "Blah with html";
text1 = ""; //the same as text2, only the last character is highlighted.
text2 = ""; //current string, which will be written.
count = 0; //char index in string text
count2 = 0; //number of strings
text = msg[0].split(""); //text - string written
function writetext() { //show strings above on screen
text1 = text2 + "<font color='#FFFFFF'>" + text[count] + "</font>";
text2 += text[count];
document.all["nothing"].innerHTML = text1; //where to write
if (count < text.length-1){
count++;
setTimeout('writetext()', 34);
}
else { //if this string is written, get the new string
count = 0;
if (count2 != 14) { //write 14 strings
count2++;
text2 += ""; //a new line
text = eval('msg['+count2+'].split("")') //get the new string to text
setTimeout('writetext()', 1);
}
}
}
</script>
<script language="JavaScript">
function disableselect(e){
return false
}
function reEnable(){
return true
}
//if IE4+
document.onselectstart=new Function ("return false")
document.oncontextmenu=new Function ("return false")
//if NS6
if (window.sidebar){
document.onmousedown=disableselect
document.onclick=reEnable
}
</script>
</body>
</html>
For whatever reason, I can't get this to work and I can't establish why ._. I've been looking it over for a good few hours now.
your code have some errors for example:
setTimeout(writetext,34)
//count =0 inside the function make an non ending loop
i modified your code :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Happy Valentine</title>
<script>
msg1 = "Blah blah with html";
msg2 = " Blah with html";
count = 0;
count2 = 0;
function writetext() {
if (count < msg1.length){
document.getElementById("text").innerHTML += msg1.charAt(count);
count++;
setTimeout(writetext, 50);
}
else {
if (count2 < 14){
document.getElementById("text").innerHTML += msg2.charAt(count2);
count2++;
setTimeout(writetext, 50);
}
}
}
</script>
</head>
<body>
<button onclick="writetext()">Click me</button>
<p id="text"></p>
</body>
</html>
You can use this code and adapt it to what you need.
<!DOCTYPE html>
<html>
<body>
<h1>Typewriter</h1>
<p id="demo"></p>
<script>
var i = 0;
var txt = 'Lorem ipsum dummy text blabla. af \n af';
var speed = 50;
document.onload=typeWriter()
function typeWriter() {
if (i < txt.length) {
document.getElementById("demo").innerHTML += txt.charAt(i).replace("\n","<br>");
i++;
setTimeout(typeWriter, speed);
}
}
</script>
</body>
</html>
And your original code, tweaked to work:
<html>
<head>
<title>Happy Valentine</title>
<style type="text/css">
body {
background: black url("http://www.robodesign.ro/files/gallery/original/love_bites.jpg");
background-repeat: repeat;
background-position: center;
background-attachment: fixed;
}
</style>
</head>
<body onload=writetext() onLoad="setTimeout('delayer()', 2000)">
<p align=center id="printto"></p>
<script>
msg = new Array(); //strings written in screen
msg[0] = "Blah with html \n Nextline";
text1 = ""; //the same as text2, only the last character is highlighted.
text2 = ""; //current string, which will be written.
count = 0; //char index in string text
count2 = 0; //number of strings
text = msg[0].split(""); //text - string written
function writetext() { //show strings above on screen
text1 = text2 + "<font color='#FFFFFF'>" + text[count] + "</font>";
text2 += text[count];
document.getElementById("printto").innerHTML = text1.replace("\n","<br>"/*seamles neqlining*/); //where to write
if (count < text.length-1){
count++;
setTimeout('writetext()', 34);
}
else { //if this string is written, get the new string
count = 0;
if (count2 != 14) { //write 14 strings
count2++;
text2 += ""; //a new line
text = eval('msg['+count2+'].split("")') //get the new string to text
setTimeout('writetext()', 1);
}
}
}
</script>
<script>
function disableselect(e){
return false
}
function reEnable(){
return true
}
//if IE4+
document.onselectstart=new Function ("return false")
document.oncontextmenu=new Function ("return false")
//if NS6
if (window.sidebar){
document.onmousedown=disableselect
document.onclick=reEnable
}
</script>
</body>
</html>

How to Pass Textbox Value from One Page to another?

I have 3 Files.
index.html
code.gs and
display.html
index.html
<!DOCTYPE html>
<html>
<head>
<style>
.my_text
{
font-family: Tahoma;
font-size: 13px;
font-weight: normal;
}
</style>
<base target="_top">
<script>
function displayMessage() {
var searchTerm;
searchTerm = document.getElementById('idSrchTerm').value;
console.log('searchTerm: ' + searchTerm );
google.script.run.withSuccessHandler(handleResults).processForm(searchTerm.replace("'","\'"));
}
function handleResults(results){
var length=results.length;
var table = document.getElementById("output");
var count = document.getElementById("count");
for(var i=0;i<length;i++)
{
var item=results[i];
item=item.split("|~|");
count.innerHTML = "Total Records Found : " + length;
table.innerHTML +="</br><a href='"+item[1]+"' target='_blank'>"+item[0]+"</a></br> <B>Owner: </B>" +item[3]+ " </br><B>Last modified: </B>"+item[2]+ " </br> <B>File Size: </B>"+item[4]+"</br>";
}
}
function clearBox(elementID)
{
document.getElementById("output").innerHTML = "";
document.getElementById("count").innerHTML = "";
}
</script>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<div class="container">
<p class = "my_text"><input type="text" id="idSrchTerm" name="search" class = "my_text" >
<input type="button" value="Search Drive" name="submitButton" class = "my_text" onClick="clearBox(); displayMessage();" />
<?var url = getScriptUrl();?><a target="_blank" href='<?=url?>?page=display'><input type="button" value="Open In New Tab" name="submitButton" class = "my_text" onClick="clearBox(); displayMessage();" value='display.html'/></a>
</div>
<div id = "count" class = "my_text">
</div>
<div id ="output" class = "my_text">
</div>
</body>
</html>
code.gs
var scriptProperties = PropertiesService.getScriptProperties();
function doGet(e) {
Logger.log( Utilities.jsonStringify(e) );
if (!e.parameter.page) {
return HtmlService.createTemplateFromFile('index').evaluate();
}
return HtmlService.createTemplateFromFile(e.parameter['page']).evaluate();
return HtmlService.createHtmlOutputFromFile('display');
}
function getScriptUrl() {
var url = ScriptApp.getService().getUrl();
return url;
}
function SearchFiles(searchTerm) {
var searchFor ="fullText contains '" + searchTerm + "'"; //single quotes are needed around searchterm
var userProperties = PropertiesService.getUserProperties();
userProperties.setProperty('SQuery', searchTerm);
var userProperties = PropertiesService.getUserProperties();
var SQuery = userProperties.getProperty('SQuery');
Logger.log(SQuery);
var names = [];
var files = DriveApp.searchFiles(searchFor);
var searchQ = searchTerm;
while (files.hasNext()) {
var file = files.next();
var fileId = file.getId();// To get FileId of the file
var lm = file.getLastUpdated();
var OType = file.getOwner().getName();
var fsize = file.getSize()
var name = file.getName()+"|~|"+file.getUrl()+"|~|"+lm+"|~|"+OType+"|~|"+fsize+"|~|"+searchQ; // Im concatenating the filename with file id separated by |~|
names.push(name); // adding to the array
Logger.log(file.getUrl());
}
return names; // return results
}
// Process the form
function processForm(searchTerm) {
var resultToReturn;
Logger.log('processForm was called! ' + searchTerm);
resultToReturn = SearchFiles(searchTerm);
Logger.log('resultToReturn: ' + resultToReturn);
return resultToReturn; // return the results
}
display.html
<!DOCTYPE html>
<html>
<head>
<style>
.my_text
{
font-family: Tahoma;
font-size: 13px;
font-weight: normal;
}
</style>
<base target="_top">
<script>
function displayMessage() {
var searchTerm;
searchTerm = document.getElementById('idSrchTerm').value;
console.log('searchTerm: ' + searchTerm );
google.script.run.withSuccessHandler(handleResults).processForm(searchTerm.replace("'","\'"));
}
function handleResults(results){
var length=results.length;
var table = document.getElementById("output");
var count = document.getElementById("count");
for(var i=0;i<length;i++)
{
var item=results[i];
item=item.split("|~|");
count.innerHTML = "Total Records Found : " + length;
table.innerHTML +="</br><a href='"+item[1]+"' target='_blank'>"+item[0]+"</a></br> <B>Owner: </B>" +item[3]+ " </br><B>Last modified: </B>"+item[2]+ " </br> <B>File Size: </B>"+item[4]+"</br>";
}
}
function clearBox(elementID)
{
document.getElementById("output").innerHTML = "";
document.getElementById("count").innerHTML = "";
}
</script>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body onload ="clearBox(); displayMessage();">
<div class="container">
<p class = "my_text">
<input type="text" id="idSrchTerm" name="search" class = "my_text" value = "outing" >
</div>
<div id = "count" class = "my_text">
</div>
<div id ="output" class = "my_text">
</div>
</body>
</html>
actually the output of index.html and output.html are the same they have textbox and the other one has a button. This code is working my only proble here is how can I pass textbox value from index.html to textbox value of display.html
This is what index.html looks like
and this is what display.html looks like
my only target here is to pass textbox value from one site to another and from that I can run my code <body onload> Thats all i need pass textbox value from another textbox from other site TYSM for help
Ty local storage
save the variable
localStorage.setItem('NameOfLocalStorage',Value);
Get the value
localStorage.getItem('NameOfLocalStorage');
You can send data via link, example:
window.location.href = "output.html?" + encodeURIComponent('blah blah bla')
and you can retrive data in output.html
var data = decodeURIComponent(window.location.search.substr(1))

How to remove checkboxes in the form

function newCheckbox(){
var aLabel = document.form1.getElementsByTagName('label');
var last = aLabel[aLabel.length-1];
var label = document.createElement('label');
label.appendChild(Box(aLabel.length));
label.appendChild(document.createTextNode(' '+document.getElementById('text').value));
last.parentNode.insertBefore(label, last);
document.getElementById('text').value = '';
}
function Box(num){
var elm = null;
try {
elm=document.createElement('<input type="checkbox" id="chk'+num+'">');
}
catch(e) {
elm = document.createElement('input');
elm.setAttribute('type', 'checkbox');
elm.id='chk'+num;
}
return elm;
}
function delBoxes(){
var texts = document.form1.getElementsByTagName('label');
for(var i = 0; i<texts.length-1; i++){
var chbox=Box[i];
txt = texts[i];
if(chbox.checked){
chbox.parentNode.removeChild(chbox);
txt.parentNode.removeChild(txt);
}
}
}
form{
color:blue;
font-weight:bold;
margin:100 0 0 50;
font-weight:bold;
margin-left:120;
padding:100;
}
label{
display:block;
}
input{
color:blue;
background-color:pink;
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="#" name="form1">
<div>
<label>Checkbox text:<input type="text" id="text"></label>
<input type="button" onclick="newCheckbox();"value="add">
<input type="button" value="Delete" onclick = "delBoxes();"/>
</div>
</form>
</body>
</html>
I want to have a dynamic page that allows a user to add checkboxes to the page. Checkbox content is the input in the textbox.
When the user pushes the “add”-button checkboxes are created and shown. The user must have the ability to remove checkboxes by marking them. The code can add a new checkbox to the form but the deleting function does not work.
It seems that chbox is not created and the if-statement does nothing in the function delBoxes.
Any suggestions?
Replace the whole script you have with this :
function newCheckbox() {
var aLabel = document.form1.getElementsByTagName('label');
var last = aLabel[aLabel.length-1];
var label = document.createElement('label');
label.appendChild(Box(aLabel.length));
label.appendChild(document.createTextNode(' '+document.getElementById('text').value));
last.parentNode.insertBefore(label, last);
document.getElementById('text').value = '';
}
function Box(num) {
var elm = null;
try {
elm=document.createElement('<input type="checkbox" class="chk">');
}
catch(e) {
elm = document.createElement('input');
elm.setAttribute('type', 'checkbox');
elm.className='chk';
}
return elm;
}
function delBoxes(){
var texts = document.form1.getElementsByTagName('label');
var chbox = document.form1.getElementsByClassName('chk');
for(var i = 0; i<texts.length-1; i++){
if(chbox[i].checked){
chbox[i].parentNode.removeChild(chbox[i]);
texts[i].parentNode.removeChild(texts[i]);
}
}
}

Categories