Inserting javascript array into HTML form - javascript

I'm completly new to js, I know a bit of Python but I get confused combining JS with HTML.
I'm trying convert an array into a HTML dropdown list but I can't seem to get it to work.
<HEAD>
<TITLE>Exercise Arrays</TITLE>
</HEAD>
<BODY>
<script>
var city;
var userInput = [];
while (city !== "stop") {
city = prompt('Please enter a city or type: "stop" to end');
if (city === "stop") {
break;
}
else {
userInput.push(city)
}
}
document.write("<h1>Exercise arrays </h1>")
document.write("<h2> States: </h2>")
document.write("<form><select>" + city + "</select></form>")
</script>
</table>
</BODY>
</HTML>

Loop your list and add option elements to your dropdown. I restructured the static parts to just HTML and access the select via its id here:
var city;
var userInput = [];
while (true) {
city = prompt('Please enter a city or type: "stop" to end');
if (city === "stop") {
break;
}
else {
userInput.push(city)
}
}
// For each item referred to as `city`, add an option
userInput.forEach(city => dropdown.add(new Option(city)));
<h1>Exercise arrays</h1>
<h2> States: </h2>
<select id="dropdown"></select>

Related

How to have a variable not reset when refreshing my website

<script>
var sum = 0;
var pressYet = false;
function changeIt() {
if(pressYet == false){
sum++;
document.getElementById('test').innerHTML = sum;
pressYet = true;
} else {
document.getElementById('test').innerHTML = "You have already pressed the button";
document.getElementById("button").style.visibility = "hidden";
}
}
</script>
<div id="test">
<b> <var> Test </ var> </b>
</div>
<button onclick="changeIt()" id = "button" >Press If you are here</button>
SO I have this sweet epic button on my website, its very cool, but I want to make it better. I was wondering how to make the variable 'sum' not reset every time I refresh my website. I know there's a term for that but for the life of me I cannot figure it out. I want it so every time someone presses the button, 'sum' gets added one to it and that number would be permanent. So over time that number gets very large.
I am very new to HTML so please be kind to me.
You can save the value to localStorage and then retrieve it from localStorage after page load. Then on the basis of the data you can adjust the page. I have slightly modified your code here
var sum = 0;
var pressYet = localStorage.getItem('pressYet');
function changeIt() {
if (pressYet == null) {
sum++;
document.getElementById('test').innerHTML = sum;
pressYet = true;
localStorage.setItem('pressYet', pressYet);
} else {
document.getElementById('test').innerHTML = "You have already pressed the button";
document.getElementById("button").style.visibility = "hidden";
}
}
(function init() {
if (localStorage.getItem('pressYet') != null || localStorage.getItem('pressYet') != "") {
document.getElementById('test').innerHTML = "You have already pressed the button";
document.getElementById("button").style.visibility = "hidden";
}
})();
<div id="test">
<b> <var> Test </ var> </b>
</div>
<button onclick="changeIt()" id="button">Press If you are here</button>
You can check out the demo https://jsfiddle.net/5jyrk6s8/

Why is if...else statement only compares single word values?

I am making a quiz app that will basically fetch the questions and answers from an API and display it to the webpage. It works fine, but the error handling isn't working. I have a if...else statement that will check if a user has selected the right answer, and if they did, play a sound and display "Nice job" to the user. If they did not, then tell the user that they need to try again. The behavior that I'm getting is very weird. Sometimes when I have chose the correct answer, it says it is not correct. It happens when there is spaces within the answer. For single words such as "true", "false" or "Hello" works fine. I logged the answer to the console stored in a variable called answer_container, when I logged it to the console, the answer and my choice are exactly the same. I have tried using === and == operators to see if that would work, but the result is the same. I have posted the full code including my HTML so that you can see what it is happening. Note it took me couple of tries to get the weird behavior to display.
Here is what I have tried:
var showAnswer = document.getElementById('showAnswer');
var button_score = document.getElementById('ShowScore');
var answer_container;
var url = 'https://opentdb.com/api.php?amount=1';
var score = 0;
var html_container = [];
async function fetchData() {
document.getElementById('next').disabled = true;
document.getElementById('msgSuccess').innerHTML = '';
document.getElementById('check').disabled = false;
document.getElementById('showAnswer').disabled = false;
var getData = await fetch(url);
var toJS = await getData.json();
answer_container = toJS.results[0].correct_answer;
var container = [];
for (var i = 0; i < toJS.results[0].incorrect_answers.length; i++) {
container.push(toJS.results[0].incorrect_answers[i]);
}
container.push(toJS.results[0].correct_answer);
container.sort(func);
function func(a, b) {
return 0.5 - Math.random();
}
html_container = [];
container.forEach(function(choices) {
html_container.push(`
<option value=${choices}>
${choices}
</option>
`)
});
document.getElementById('choice').innerHTML = html_container.join();
if (toJS.results[0].type === 'boolean') {
document.getElementById('type').innerHTML =
`This question is a ${toJS.results[0].category} question <br>
It is a true/false question<br>
Difficulty level: ${toJS.results[0].difficulty} <br>
Question: ${toJS.results[0].question}<br>
`;
} else {
document.getElementById('type').innerHTML =
`This question is a ${toJS.results[0].category} question <br>
It is a ${toJS.results[0].type} choice question <br>
Difficulty level: ${toJS.results[0].difficulty} <br>
Question: ${toJS.results[0].question}<br>
`;
}
}
fetchData();
showAnswer.addEventListener('click', function() {
document.getElementById('answer_element').innerHTML = "The answer to this question is " + answer_container;
document.getElementById('answer_element').style.display = "block";
setTimeout(function() {
document.getElementById('answer_element').style.display = "none";
}, 3000);
});
function check() {
var select_answer = document.getElementById('choice').value;
var audio = document.getElementById('audio');
if (select_answer == answer_container) {
score++;
document.getElementById('showAnswer').disabled = true;
document.getElementById('msgSuccess').innerHTML = "Nice job, keep going!";
document.getElementById('next').disabled = false;
document.getElementById('check').disabled = true;
audio.play();
console.log(answer_container);
}
if (select_answer != answer_container) {
score--;
document.getElementById('msgSuccess').innerHTML = "Keep trying, you will get it!";
document.getElementById('next').disabled = true;
console.log(answer_container);
}
}
<!DOCTYPE html>
<html>
<head>
<title>
Quiz App
</title>
</head>
<body>
<div id="type">
</div>
<label>
Select Your Answer...
</label>
<select id="choice">
</select>
<button id="showAnswer">
Show Answer
</button>
<p id="answer_element">
</p>
<button onclick="check()" id="check">
Check
</button>
<p id="msgSuccess">
</p>
<button id="next" onclick="fetchData()">
Next Question
</button>
<audio id="audio">
<source src="https://www.theharnishes.com/khanacademy.mp3" type="audio/mp3">
</audio>
</body>
</html>
You're using the expression select_answer == answer_container to determine if the choice is the correct answer.
select_answer comes from the value attribute of the option you've selected. However, when an answer value contains whitespace, HTML interprets only up to the first whitespace as the "value". When answers like North America come up, the option's value attribute is only North.
When generating your options in your HTML, you need to properly encapsulate them in double quotes ", like so:
html_container.push(`
<option value="${choices}">
${choices}
</option>
`)
Tangential, but it would probably be cleaner if you generated your elements with document.createElement() and Node.appendChild(); in this instance the quotes required to properly set the value attribute on each option would have been added for you.
Nice game!
The issue here is the text is getting truncated on whitespace in the HTML, so the value you're comparing it too doesn't match.
You need quotes in the HTML option to preserve white space.
<option value=${choices} <- picks the first word
<option value="${choices}" <- allows the whole string with spaces
var showAnswer = document.getElementById('showAnswer');
var button_score = document.getElementById('ShowScore');
var answer_container;
var url = 'https://opentdb.com/api.php?amount=1';
var score = 0;
var html_container = [];
async function fetchData() {
document.getElementById('next').disabled = true;
document.getElementById('msgSuccess').innerHTML = '';
document.getElementById('check').disabled = false;
document.getElementById('showAnswer').disabled = false;
var getData = await fetch(url);
var toJS = await getData.json();
console.log(toJS)
answer_container = toJS.results[0].correct_answer;
var container = [];
for (var i = 0; i < toJS.results[0].incorrect_answers.length; i++) {
container.push(toJS.results[0].incorrect_answers[i]);
}
container.push(toJS.results[0].correct_answer);
container.sort(func);
function func(a, b) {
return 0.5 - Math.random();
}
html_container = [];
container.forEach(function (choices) {
html_container.push(`
<option value="${choices}">
${choices}
</option>
`)
});
document.getElementById('choice').innerHTML = html_container.join();
if (toJS.results[0].type === 'boolean') {
document.getElementById('type').innerHTML =
`This question is a ${toJS.results[0].category} question <br>
It is a true/false question<br>
Difficulty level: ${toJS.results[0].difficulty} <br>
Question: ${toJS.results[0].question}<br>
`;
}
else {
document.getElementById('type').innerHTML =
`This question is a ${toJS.results[0].category} question <br>
It is a ${toJS.results[0].type} choice question <br>
Difficulty level: ${toJS.results[0].difficulty} <br>
Question: ${toJS.results[0].question}<br>
`;
}
}
fetchData();
showAnswer.addEventListener('click', function () {
document.getElementById('answer_element').innerHTML = "The answer to this question is " + answer_container;
document.getElementById('answer_element').style.display = "block";
setTimeout(function () {
document.getElementById('answer_element').style.display = "none";
}, 3000);
});
function check() {
var select_answer = document.getElementById('choice').value;
var audio = document.getElementById('audio');
console.log(select_answer, answer_container)
if (select_answer == answer_container) {
score++;
document.getElementById('showAnswer').disabled = true;
document.getElementById('msgSuccess').innerHTML = "Nice job, keep going!";
document.getElementById('next').disabled = false;
document.getElementById('check').disabled = true;
audio.play();
console.log(answer_container);
}
if (select_answer != answer_container) {
score--;
document.getElementById('msgSuccess').innerHTML = "Keep trying, you will get it!";
document.getElementById('next').disabled = true;
console.log(answer_container);
}
}
<!DOCTYPE html>
<html>
<head>
<title>
Quiz App
</title>
</head>
<body>
<div id="type">
</div>
<label>
Select Your Answer...
</label>
<select id="choice">
</select>
<button id="showAnswer">
Show Answer
</button>
<p id="answer_element">
</p>
<button onclick="check()" id="check">
Check
</button>
<p id="msgSuccess">
</p>
<button id="next" onclick="fetchData()">
Next Question
</button>
<audio id="audio">
<source src="https://www.theharnishes.com/khanacademy.mp3" type="audio/mp3">
</audio>
</body>
</html>

how to register unique values? in the spreadsheet google app script web

i need a help to register only unique values ​​inside the google spreadsheet behind the web script app
currently to save I use this script, practical find a way to block the launch if you already have values ​​the same values ​​in the spreadsheet.
basically there are two fields "cod" and "val"
if "cod" and "val" have already been registered before, it would need to show a message that these data are repeated.
I tried to do a check, but you can only do it in one "cod" field,
I would like to do it in both "cod" and "val" fields
https://docs.google.com/spreadsheets/d/1ZfIqw6_pkt1AdWsayyk1LdW_I6lU2yjsY1VfxfJneCA/edit#gid=0
function save_on_sheet(Data){
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1ZfIqw6_pkt1AdWsayyk1LdW_I6lU2yjsY1VfxfJneCA/edit#gid=0");
var ws = ss.getSheetByName("page");
const cod = ws.getRange(2, 1, ws.getLastRow()-1, 1).getValues().map(r => r[0].toString().toLowerCase());
const posicaoIndex = cod.indexOf(Data.cod.toString().toLowerCase());
if (posicaoIndex === -1) {
ws.appendRow([
Data.cod,
Data.val
])
return 'NEW';
} else {
return 'DUPLICATE';
}
}
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<label for="cod">COD:</label>
<input type="text" id="cod"><br><br>
<label for="val">VALUE:</label>
<input type="text" id="val"><br><br>
<input type="submit" value="SAVE UNIQUE SHEET" onclick="save()">
</body>
<script>
function save(){
Data = {}
Data.cod = document.getElementById("cod").value;
Data.val = document.getElementById("val").value;
google.script.run.withSuccessHandler(retorno).save_on_sheet(Data);
}
function retorno(mensagem_retorno){
alert(mensagem_retorno);
}
</script>
</html>
You can refer to this sample code:
function save_on_sheet(Data){
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1ZfIqw6_pkt1AdWsayyk1LdW_I6lU2yjsY1VfxfJneCA/edit#gid=0");
var ws = ss.getSheetByName("page");
const dataVal = ws.getRange(2,1,ws.getLastRow()-1, 2).getDisplayValues();
Logger.log(dataVal);
for(var i=0; i<dataVal.length;i++){
var rowData = dataVal[i];
if(rowData[0]==Data.cod.toString().toLowerCase() && rowData[1]==Data.val.toString().toLowerCase()){
//Exit function, duplicate found
return 'DUPLICATE';
}
}
//No duplicate found. Append new data
ws.appendRow([
Data.cod,
Data.val
]);
return 'NEW';
}
What it does?
Get cod and values data in the spreadsheet using Range.getDisplayValues() which will return a 2-d array of string values.
Loop each row value and compare cod and values to Data.cod and Data.values. If match found, return "DUPLICATE", if no match found, append the Data and return "NEW"

Will this loop correctly and be able to list tag names?

I want to prompt user to enter a tag and it will list it in the console.log and will ask again until they type "quit". if that happens then I will use the documentwrite to list in the innertext what the previous tags been searched for.
var selector = prompt("Please enter a selector: ");
var selectorr = document.getElementsByTagName(selector);
var breaker = "quit";
breaker = false;
var textlogger = "elements have been found that match the selector ";
var lengthfinder = selectorr.length;
while(true) {
console.log(lengthfinder + textlogger + selector);
if (selector == breaker) {
for (var i=0; i<divs.length; i++) {
document.write.innerText(textlogger);
}
}
}
If you wanna try jQuery and something fun, take this:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Loop with jquery deferred</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var loop = function () {
return $.Deferred(function (deferred) {
var selector = prompt("Please enter a selector: ");
var quit = 'quit';
var selectors = [];
while (selector && selector != quit) {
selectors.push(selector);
var elements = $(selector);
console.log(elements.length + " elements have been found that match the selector " + selector);
selector = prompt("Please enter a selector: ");
}
if (selector)
{
deferred.resolve(selectors);
}
else
{
deferred.reject();
}
}).promise();
};
$(function () {
loop().done(function (selectors) {
$($.map(selectors, function (item, index) {
return '<div>' + item + '</div>';
}).join('')).appendTo($('body'));
});
});
</script>
</head>
<body>
<div>
<iframe src="http://stackoverflow.com/questions/40392515/will-this-loop-correctly-and-be-able-to-list-tag-names"/>
</div>
</body>
</html>
Here is the version with comments and suggestions on where to put your necessary code for it to work.
Code Preview
var breaker = "quit",
textlogger = "elements have been found that match the selector ",
textList = new Array();
while (true) {
var selector = prompt("Please enter a selector: ");
if (selector == breaker) {
/*
Write your necessary output here
*/
/*
After output you break out
*/
break;
} else {
/*
Write It inside list
*/
textList.push(selector);
}
/*
Write necessary output in console
*/
console.log(selector);
}
I want to prompt user to enter a tag and it will list it in the
console.log and will ask again until they type "quit"
while ("quit" !== prompt("Tag name selector, type `quit` to exit", "quit")) {
console.log("in loop");
}
console.log("exit loop");
I will use the documentwrite to list in the innertext what the
previous tags been searched for.
Either you use: document.write("some text") to append to existing dom or you can use selectorr[i].innerText="some text"
Here is my small example that might help you:
var selector;
while ("quit" !== (selector = prompt("Tag name selector. Use `quit` to cancel search", "quit"))) {
var elements = document.getElementsByTagName(selector);
var count = elements.length;
while (count--) {
elements[count].innerHTML += " [matched]";
}
}
<span>This is my <span> tag 1</span>
<p>This is my <p> tag 1</p>
<div>This is my <div> tag 2</div>
<p>This is my <p> tag 3</p>
<span>This is my <span> tag 2</span>

Inserting User Input Values into a Function

I am trying to take a user input value that is entered through an html input box, and have it as a value within my function (the negKeyword function in my code to be more specific). The problem that I think is happening is this input value is stored as a variable, so when the code is first stored in memory it is stored as "", since the user has not inputed anything yet. How do I get it so when the user inputs something it replaces blank or "" with what ever the user inputs?
What I basically want to happen next is the user will click a button, it will then compare what the user inputs to what the "negKeyword" function outputs and give a result on whether they match or not (this action is demonstrated in my booleanKeyword function in my code).
Here is my code.
var input = document.getElementById("input").value;
var arr = ['no', 'not', 'checked'];
var text = ''; //JS output variable.
var keyword = 'leak'; //Individual keyword.
function negKeyword() {
for (i = 0; i < arr.length; i++) {
if (text == input) { break; }
text = arr[i] + ' ' + keyword;
}
return text;
}
function booleanKeyword() {
if (input == negKeyword()) {
document.getElementById("result").style.color="green";
document.getElementById("result").innerHTML="Match";
} else {
document.getElementById("result").style.color="red";
document.getElementById("result").innerHTML="No Match";
}
}
document.getElementById("result2").innerHTML=keyword;
<label for="Full Negative Keyword">Negative Keyword</label> <input id="input" type="text" />
<div id="message">Result: <span id="result"></span></div>
<div id="message">Keyword: <span id="result2"></span></div>
<button id="test" onclick="booleanKeyword()">Click to Test</button>
You can retrieve the input's value again, by getting it and assigning to the same variable (but inside the function that is called after the button click).
var input = document.getElementById("input").value;
var arr = ['no', 'not', 'checked'];
var text = ''; //JS output variable.
var keyword = 'leak'; //Individual keyword.
function negKeyword() {
input = document.getElementById("input").value;
for (i = 0; i < arr.length; i++) {
if (text == input) { break; }
text = arr[i] + ' ' + keyword;
}
return text;
}
function booleanKeyword() {
input = document.getElementById("input").value;//The variable is reassigned, only after the click
if (input == negKeyword()) {
document.getElementById("result").style.color="green";
document.getElementById("result").innerHTML="Match";
} else {
document.getElementById("result").style.color="red";
document.getElementById("result").innerHTML="No Match";
}
}
document.getElementById("result2").innerHTML=keyword;
Edit: added the same code to negKeyword() function as it requires the input too.
It is not working because your variable input is always "". You have to assign new value to it each time the button is clicked. I just moved your code for input in BooleanKeyword() function. Now everything is working fine.
Everytime when something like this is not working, just try to log/alert values.
For example you could just alert(input + ' ' + negKeyword()); on top of booleanKeyword() function and you would see problem by yourself.
var input;
var arr = ['no', 'not', 'checked'];
var text = ''; //JS output variable.
var keyword = 'leak'; //Individual keyword.
function negKeyword() {
for (i = 0; i < arr.length; i++) {
if (text == input) { break; }
text = arr[i] + ' ' + keyword;
}
return text;
}
function booleanKeyword() {
input = document.getElementById("input").value;
if (input == negKeyword()) {
document.getElementById("result").style.color="green";
document.getElementById("result").innerHTML="Match";
} else {
document.getElementById("result").style.color="red";
document.getElementById("result").innerHTML="No Match";
}
}
document.getElementById("result2").innerHTML=keyword;
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<label for="Full Negative Keyword">Negative Keyword</label> <input id="input" type="text" />
<div id="message">Result: <span id="result"></span></div>
<div id="message">Keyword: <span id="result2"></span></div>
<button id="test" onclick="booleanKeyword()">Click to Test</button>
</html>

Categories

Resources