How do I get a HTML div element to loop using javascript? - javascript

I have a block of code, a quiz creation template, and i need the block of code for the question and possible answers to be looped, for however many times the user asks for. I have been trying for hours and im really not sure whats wrong.
<div id="questionform" class="modal">
I already have the amount of questions the user would like under this line of code.
var amount = prompt("Please enter the amount of questions you would like", "<amount goes here>");
below is the javascript i am using to try and loop the writing within the div.
var i;
var amount;
var contents = document.getElementById("questionform").innerHTML;
for (i = 1; i=amount; i++) {
a.document.write(contents);
}

Your condition in your for-loop is wrong. You have an assignment instead of an evaluation.
for (i = 1; i=amount; i++)
You should be creating elements and appending them to the DOM. Avoid using document.write. Also, please begin indexing at zero, unless you need to start at 1.
Update
If you provide a name attribute to your input fields, they will be submitted with the form on submit.
input.setAttribute('name', 'answer[]');
When you hit submit, the input field values will be sent to the server as:
answer=foo&answer=bar
or:
{ "answer" : [ "foo", "bar" ] }
Refer to this if you are still confused: POST an array from an HTML form without javascript
Example
let amount = prompt("Please enter the amount of questions you would like", 5);
let questionForm = document.getElementById("question-form");
let answerList = questionForm.querySelector(".answer-list");
for (let i = 0; i < amount; i++) {
let inputWrapper = document.createElement('DIV');
let label = document.createElement('LABEL');
let input = document.createElement('INPUT');
input.setAttribute('type', 'text');
input.setAttribute('name', 'answer[]');
label.textContent = 'Answer ' + String.fromCharCode(i + 65) + ': ';
inputWrapper.classList.add('input-wrapper');
inputWrapper.appendChild(label);
inputWrapper.appendChild(input);
answerList.appendChild(inputWrapper);
}
.input-wrapper {
margin-bottom: 0.25em;
}
.input-wrapper label {
display: inline-block;
width: 5em;
font-weight: bold;
}
<form id="question-form" class="modal">
<div class="answer-list"></div>
<button type="submit">Submit</button>
</form>

Related

Change h1 using javascript switch statement based on input

I need to know how to get the h1 sun emoji to change when user input less than or equal to 0.
I feel like I have the logic but just need to code.
Once the user inputs a temperature less than 0 the h1 needs to change to a certain emoji or content.
Can I get some advice please. I am struggling here. this is my code:
function question() {
let city = prompt("what city do you live in?");
let temp = prompt("What temperature is it?");
let h1 = document.queryselector("h1");
h1.innerHtml = "Currently" + temp + "degrees" + " in " + city;
}
function change() {
switch (true) {
case (temp <= 0):
document.getElementById("h1").innerHtml = "Currently" + temp + "degrees" + "in " + city;
}
}
<h1>
sun emoji
</h1>
<h1 class="temperature">
Currently 21 degrees in Tokyo
</h1>
<h2>
13 degrees / <strong>23 degrees</strong>
</h2>
The h1 has to change to a different emoji based on the users response of less than or equal to 0.
Along with the emoji I need to input of the user city to change along with it.I just need the h1 section to change.Should I use a switch or if else statement?
Firstly, you have multiple h1 elements - queryselector only returns the first one, so in this case you would be replacing the emoji, not the text.
It would be prudent to give the various elements that you intend to edit id fields.
<h1 id="emoji-el">
sun emoji
</h1>
<h1 id="temp-details" class="temperature">
Currently 21 degrees in Tokyo
</h1>
Now you can use queryselector to select the correct elements.
Secondly, I'd like to say that it is good practice to have every function have a single responsibility - for example, one function get a correct emoji, while another puts things into elements.
Given this, I would use an if list because of the way your condition is structured:
function getEmoji(temp) {
if (temp < 0) return ❄️;
if (temp < 13) return ☁;
return ☀️;
}
You can likely use emojis directly for HTML text values, and if you only use upper limits like I did you don't need elses. IMO this is the nicest way.
You final function would look something like this:
function questionUser() {
const city = prompt("What city do you live in?");
const temp = prompt("What temperature is it?");
updatePage(temp, city);
}
function updatePage(temp, city) {
const emojiElement = document.queryselector("#emoji-el");
const tempElement = document.queryselector("#temp-details");
const emoji = getEmoji(Number(temp));
emojiElement.innerHtml = emoji;
tempElement.innerHtml = `Currently ${temp} degrees in ${city}.`;
}
This way you would be able to re-use the update logic elsewhere, and also it is clear what every function does.
Hope this helps.
Can achieve the same result with switch or if statement.
You just have to trigger the function on onChange or onBlur.
It's advisable to use classNames or id's for your html element, which makes retrieving specific elements easier.
Switch is suitable if your conditions have a fixed value. In this case a a ternary (conditional operator) would be an idea.
Here's an exemplary snippet demoing ternary or switch to determine the 'emoji' to display, based on the given temperature. It uses event delegation for handling the button click.
document.addEventListener(`click`, handle);
function handle(evt) {
// act only if button#showTemperatures is clicked
if (evt.target.id === `showTemperatures`) {
return question();
}
}
function emo(temp) {
const emojiTxt = temp < 15 ? `*Brr**` :
temp < 25 ? `*nice*` :
temp < 30 ? `*it's getting hot here*` : `*tropical!*`;
document.querySelector(`.emoji`).textContent = emojiTxt;
}
/* using switch is possible, but you need something extra */
function emoSwitch(temp) {
const lt = n => temp < n;
let emojiTxt = ``;
switch (true) {
case lt(10):
emojiTxt = `*Brr*`;
break;
case lt(25):
emojiTxt = `*nice*`;
break;
case lt(30):
emojiTxt = `*it's getting hot here*`;
break;
default:
emojiTxt = `*tropical!*`;
}
document.querySelector(`.emoji`).textContent = emojiTxt;
}
function question() {
// id's make your coding life simple
const city = document.querySelector(`#city`).value;
const temp = document.querySelector(`#temp`).value;
// one of the values is not filled, alert
if (!city.trim() || temp < 0) {
return alert(`please fill out both fields`);
}
// fill in h1.temperature
document.querySelector(`.temperature`).textContent =
`Currently ${temp} degrees in ${city}`;
// fill in the emoji
return document.querySelector(`#switch`).checked ?
emoSwitch(temp) : emo(temp);
}
<!-- changed for demo -->
<p>
<b class="emoji"></b>
<b class="temperature">Currently 21 degrees in Tokyo</b>
</p>
<hr>
<p><input type="text" id="city"> What city do you live in?</p>
<p><input type="number" id="temp" min="0" max="55"> What temperature is it up there?</p>
<p>
<button id="showTemperatures">Fill in</button>
<input type="checkbox" id="switch">Use switch
</p>

javascript project to teach kids english alphabet

ask us to write a
In this project, you are required to implement a simple web application that allows kids in
schools to learn the basic English Alphabet. The basic idea is that, the user will choose
the number of letters he wants to learn, and when clicking on each letter, another page is
opened showing an image of something that begins with that letter. In addition, some user
interaction events are collected and stored in the localStorage object of the browser to be
used in subsequent versions of the project.
The application should look something like the following:
• It has an index.html page contains a number input and a button. The user chose
how many letters (from 1 up to 26) he wants to learn, then he presses OK.
A randomly chosen letters should be selected. For example, if the user wants to
learn 3 letters, he uses the number input field and chose 3, then presses OK and
after that he will get 3 randomly chosen letters from the English alphabet.
• The next step is for the user to click on one of the letters and then an Image is
displayed showing something that begins with that letter. Images are stored in a
folder for created for each letter (You should download some images from the
internet to use them in the project).
and i am stuck at this point that when i click in the bottun generate it generate the litters but it also diplay the images !! and i cant solve it
this is the code
var div2 =document.getElementById("div2");
var div3 =document.getElementById("div3");
var generate = document.getElementById("generate");
var input = document.getElementById("input");
var letters = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
litterImg = [];
for (let i = 0;i < 26;i++) {
litterImg[i] = 'img\\Letter.jpg';
}
console.log(litterImg[0]);
//console.log(numberOfLitters);
var randomLetter = [];
var getRandomLetter = [] ;
var getRandomLetter1 ;
var linkImg = [];
var numberOfLitters
var randomNumber=[];
var x ;
generate.addEventListener("click",function(e){
numberOfLitters = input.valueAsNumber;
for (let index = 0; index < numberOfLitters; index++) {
randomNumber[index] = Math.floor(Math.random()*26);
}
for (let index = 0; index < numberOfLitters; index++) {
x++ ;
randomLetter[index] = document.createElement("input");
randomLetter[index].setAttribute("type","button");
randomLetter[index].setAttribute("value",letters[randomNumber[index]]);
randomLetter[index].setAttribute("id",randomNumber[index]);
randomLetter[index].setAttribute("class","Letter");
div2.appendChild(randomLetter[index]);
}
for (let index = 0; index < numberOfLitters; index++) {
randomLetter[index].onclick = addImg();
function addImg(){
linkImg[index] = document.createElement("img");
linkImg[index].setAttribute("src",litterImg[randomNumber[index]]);
div3.appendChild(linkImg[index]);}
}
});
and this is the html code
<!DOCTYPE html>
<html>
<head>
<meta>
<title>Alphabet Learner</title>
</head>
<body style="background-color: salmon;">
<div id="div" class="div">
<h1>Learn the English Litters </h1>
<label >Number of Litters: </label>
<input type="number" class="input" id="input" >
<input type="button" class="generate" id="generate" value="Generate">
<div id="div2" class="div2" style="margin-left: 123px;
margin-top: 20px;">
</div>
<div id="div3" class="div3"></div>
</div>
<script src="code.js"></script>
</body>
</html>
You can get all the input elements you created with document.querySelectorAll('.div2 input') and then loop with that to know what is the id or the value of the input clicked.
...
// create allInputs variable
var allInputs;
generate.addEventListener('click', function (e) {
numberOfLitters = input.valueAsNumber
for (let index = 0; index < numberOfLitters; index++) {
randomNumber[index] = Math.floor(Math.random() * 26)
}
for (let index = 0; index < numberOfLitters; index++) {
x++
randomLetter[index] = document.createElement('input')
randomLetter[index].setAttribute('type', 'button')
randomLetter[index].setAttribute('value', letters[randomNumber[index]])
randomLetter[index].setAttribute('id', randomNumber[index])
randomLetter[index].setAttribute('class', 'Letter')
div2.appendChild(randomLetter[index])
}
/* Here you select all the input you created */
allInputs = document.querySelectorAll('.div2 input');
console.log(allInputs);
for (let index = 0; index < allInputs.length; index++) {
allInputs[index].addEventListener('click', function(e) {
/* Here you can use the allInputs[index] to get the id or the value of your input and create your image with that index or value, check your console */
console.log(allInputs[index])
console.log(allInputs[index].value)
console.log(allInputs[index].id)
});
}
})

Replace previously generated content in Javascript based on user input

I have a button on that perfroms the collatz conjecture with the push of a button, and takes in the user's input. It then prints out the steps as a list into a p tag. I wanted to know how I would override the previously created steps, as I have noticed calling the method again adds to the end of the previous list.
The main reason I'm using a list is for readability, so I don't want to get rid of it unless there's a better way of doing this.
//collatz function
function collatz (){
var step = 0;
var inputCollatz = prompt("What number do you want to add?")
if (inputCollatz <= 1){
document.getElementById("collatz").innerHTML = "No steps required, already less than or equal to 1.";
}
else if(isNaN(inputCollatz)){
document.getElementById("collatz").innerHTML = "Please add a number.";
}
else if (inputCollatz.toString().indexOf('.') != -1){
document.getElementById("collatz").innerHTML = "Whole numbers please!";
}
else{
while(inputCollatz > 1){
//needed help w/ ternary operators, still need practice with it
inputCollatz = inputCollatz % 2 ? 3 * inputCollatz + 1 : inputCollatz / 2;
step++;
var item = document.createElement("li");
var text = document.createTextNode(inputCollatz);
item.appendChild(text);
var list = document.getElementById("collatz");
list.appendChild(item);
}
document.getElementById("steps").innerHTML = "Number of steps: " + step.toString();
}
}
This is the button in html.
<button onclick="collatz()">Find the number of steps.</button><br/>
<br/>
<div id="collatz"></div>
<br/>
<div id="steps"></div>
I was suggested to clear out the collatz div before each loop, which worked.
...
else {
document.getElementById("collatz").innerHTML = '';
while(inputCollatz > 1) {
....

PHP text boxes dynamic ID generating

i would be very thankful if anyone could help me with this
i am trying to use php uploader plugin and upload multiple files.
i want to assign unique ids to the generating text box fields.
but whenever I am using a for loop to assign id , the text boxes won't show up
here is my code
var input = document.createElement('input');
input.value = task.FileName;
input.id = "textBox_";
for(var i = 0; i<0; i++){
input.id = "textBox_'.i.'";
}
document.body.appendChild(input);
}
the help will be appreciated ..
You are not appending the value of i properly. In js concatenation is done using + operator not using .
input.id = "textBox_"+i;
Place
document.body.appendChild(input);
inside the for loop like shown below as it has to generate input each time until loop ends.
for(var i = 0; i<0; i++)
{
input.id = "textBox_"+i;
document.body.appendChild(input);
}
Change input.id = "textBox_'.i.'"; to input.id = "textBox_"+i;
Concatenation in js is cone using + operator
So your code will be:
var input = document.createElement('input');
input.value = task.FileName;
input.id = "textBox_";
for(var i = 0; i<0; i++){//Condition of this loop is wrong in the sence it wont execute even once so fix it as your needs
input.id = "textBox_"+i;
document.body.appendChild(input);
}
}

Removing a text field using Javascript

I have the following code to add text fields when the function is called:
<span id="response"></span>
<script>
var qcountBox = 2;
var acountBox = 2;
var qboxName = 0;
var aboxName = 0;
function addInput()
{
var qboxName="question"+qcountBox;
var aboxName="answer"+acountBox;
if(qcountBox <=10 && acountBox <= 10)
{
document.getElementById('response').innerHTML+='<br/>Question '+qcountBox+': <input type="text" name="'+qboxName+'"/>';
document.getElementById('response').innerHTML+='<br/>Answer '+acountBox+': <input type="text" name="'+aboxName+'"/><br/>';
qcountBox ++;
acountBox ++;
}else
alert("No more than 10 questions allowed at this time.");
}
I also would like to be able to add a function to remove any new fields I have added. Any suggestions? Thanks
<script>
var qcountBox = 1;
var acountBox = 1;
var qboxName = 0;
var aboxName = 0;
function addInput()
{
var qboxName="question"+qcountBox;
var aboxName="answer"+acountBox;
if(qcountBox <=10 && acountBox <= 10)
{
document.getElementById('response').innerHTML+='<div id="'+qcountBox+'"><br/>Question '+qcountBox+': <input type="text" name="'+qboxName+'"/>';
document.getElementById('response').innerHTML+='<br/>Answer '+acountBox+': <input type="text" name="'+aboxName+'"/><br/></div>';
qcountBox ++;
acountBox ++;
}else
alert("No more than 10 questions allowed at this time.");
}
function removeInput(id)
{
document.getElementById(id).innerHTML = '';
}
You can remove any question that you added using the id of the question div (same as qboxName)
Surround each new piece of HTML in a span with a common class name. Then, find all the objects with that class name and remove them.
Add the span and class name to these:
document.getElementById('response').innerHTML+='<span class="added"> <br/>Question '+qcountBox+': <input type="text" name="'+qboxName+'"/></span>';
document.getElementById('response').innerHTML+='<span class="added"><br/>Answer '+acountBox+': <input type="text" name="'+aboxName+'"/><br/></span>';
Then, you can remove all the added spans like this:
var items = document.getElementsByClassName("added");
for (var i = 0; i < items.length; i++) {
items[i].parentNode.removeChild(items[i]);
}
Note: This is a generally better way to add your new HTML as it doesn't rewrite all previous HTML - it just adds new DOM objects:
var span = document.createElement("span");
span.className = "added";
span.innerHTML = '<br/>Question '+qcountBox+': <input type="text" name="'+qboxName+'"/><br/>Answer '+acountBox+': <input type="text" name="'+aboxName+'"/><br/>';
document.getElementById('response').appendChild(span);
You should actually create an input element in javascript and append it to your container through appendChild instead of using innerHTML +=.
You should also set an ID for those fields, not just a name. But it can be the same as theirs names.
Like this
var input = document.createElement("input");
input.type = "text";
input.name = input.id = qboxName;
document.getElementById("response").appendChild(input);
And then, you know, do the same for the other input field you need.
I know you need a text label for the boxes, or whatever, just do the same process to insert a span tag before them.
Also, I don't see a reason for those two counting variables. Instead of qcountBox and acountBox it's totally possible to have only one single counting variable. Maybe I'm wrong but shouldn't you increase this counting before setting the boxes names?
As for removing it, you can use the removeChild method, then, decrease your counting variable. like this:
function removeInput()
{
var qboxName = "question" + count;
var aboxName = "answer" + count;
document.getElementById("response").removeChild(document.getElementById(aboxName));
document.getElementById("response").removeChild(document.getElementById(aboxName));
count--;
}
Maybe if you're going to insert other elements together with these fields, like span tags for labels etc, it would be better to wrap them all up in a div or something, then simply do a removeChild to this container div only.

Categories