Stuck on buttons and text input in html - html

I'm currently working on a simple flag guessing game, where the user sees a flag and input's the country it is, but I'm finding it hard to take a value from the text input and put it into logic. My function for the button does run but doesn't make it to the if statements, seemingly not reading the text in the input.
<!DOCTYPE html>
<html>
<head>
<title>The America's</title>
</head>
<body>
<img src = "Colombia.png">
</br>
<p><em>The flag shown above is which countries flag?</em></p>
<h1 id="flag">...</h1>
<h2 id = "guess">...</h2>
<h3 id = "result">...</h3>
<input id="guessfun" type ="text">
<!--
<button id="enter">Enter</button> -->
<button id = "button_enter" onclick="guess()">Enter</button>
<script>
function guess(){
alert("f")
flag.textContent = guess.value;
if (guessfun == "Colombia"){
result.textContent = ("Yes! That's the flag of" + guess.value);
alert("Yes")
}
else if (guessfun =! "Colombia") {
result.textContent = ("No! That's the Colombian Flag!");
alert("No")
}
}
onclick = guess();
</script>
</body>
</html>
Any help would be greatly appreciated!

Not gonna lie, your code is pretty messed up. You should probably clean it up. You're trying to access variables that you've never defined(flag, guess). To access the elements, use document.getElementById(). I'm also not seeing what flag.textContent is for. You should instead directly access the input when checking.
function guess(){
var guess = document.getElementById("guessfun").textContent;
var result = document.getElementById("result");
if (guess == "Colombia"){
result.textContent = ("Yes! That's the flag of" + guess.value);
}
else if (guessfun =! "Colombia") {
result.textContent = ("No! That's the Colombian Flag!");
}
}
Additionally, you should probably remove the onclick from the bottom.

Declaring an id in the HTML does not automatically create a corresponding variable accessible through JavaScript, you must first retrieve this element thanks to its id with document.getElementById()
In the example below I use it to retrieve the entered value, then I use it again to display the result:
function guess(){
var input = document.getElementById('guessfun').value
var result = "No! That's the Colombian Flag!"
if (input == "Colombia"){
result = (`Yes! That's the flag of ${input}`);
}
document.getElementById('result').innerHTML = result
}
<img height="36px" src = "https://upload.wikimedia.org/wikipedia/commons/thumb/2/21/Flag_of_Colombia.svg/1280px-Flag_of_Colombia.svg.png">
<br>
<p><em>The flag above is the flag of which country?</em></p>
<h3 id = "result">...</h3>
<input id="guessfun" type ="text">
<button onclick="guess()">Enter</button>

replace else if (guessfun =! "Colombia") { by else {, No need Of putting else if there. Because if guess == "Colombia" dosent match then its always not equal to "Colombia".
And You Haven't Defined flag, result and guessfun
You can define them like this
const flag = document.getElementById("flag");
const result = document.getElementById("result");
const guessfun = document.getElementById("guessfun");
You Can Apply More Than One Flag, Try Below Snippet
Snippet
var currFlag;
var currId;
const v = document.getElementById("guessfun");
const r = document.getElementById("result");
const flag = document.getElementById("flag");
setFlag();
function setFlag(pre = -1){
flag.src = "";
r.innerHTML = "...";
v.value = "";
document.getElementById("guess").innerHTML = "...";
var flags = [];
flags.push(
{"Name" : "Colombia", "Src":"https://upload.wikimedia.org/wikipedia/commons/thumb/2/21/Flag_of_Colombia.svg/255px-Flag_of_Colombia.svg.png"},
{"Name" : "USA", "Src":"https://upload.wikimedia.org/wikipedia/en/thumb/a/a4/Flag_of_the_United_States.svg/220px-Flag_of_the_United_States.svg.png"},
{"Name" : "Sri Lanka", "Src":"https://image.shutterstock.com/image-vector/flag-sri-lanka-lion-vector-260nw-195385355.jpg"},
{"Name" : "UK", "Src":"https://cdn.britannica.com/25/4825-004-F1975B92/Flag-United-Kingdom.jpg"}
);
currId = getRandomId(flags.length, pre);
currFlag = flags[currId];
flag.src = currFlag.Src;
}
function guess(){
document.getElementById("guess").innerHTML = v.value;
if(v.value.toLowerCase() == currFlag.Name.toLowerCase()){
r.innerHTML = "Hooray! You Won. <a href='#' onclick='setFlag("+currId+")'>Click to Guess again<a>";
}
else{
r.innerHTML = "The Correct Answer Is: "+currFlag.Name+". <a href='#' onclick='setFlag("+currId+")'>Click to try again<a>";
}
}
function getRandomId(max, pre = -1) {
var ret;
ret = Math.floor(Math.random()*max);
if(ret > max || ret < 0 || ret == pre){ ret = getRandomId(max, pre) }
return parseInt(ret);
}
<!DOCTYPE html>
<html>
<head>
<title>The America's</title>
</head>
<body>
<img id="flag" width="50px" />
<p><em>The flag shown above is which countries flag?</em></p>
<h1 id="flag">...</h1>
<h2 id = "guess">...</h2>
<h3 id = "result">...</h3>
<input id="guessfun" type ="text">
<button id = "button_enter" onclick="guess()">Enter</button>
</body>
</html>

Related

Show div depending to value of function in apps script

I develop and web app in apps script where i can select a name. Each name is in my Sheets and is depending to a profil. I can have 2 possibilities : The name have a profil or doesn't have. In the screenshot below, Sir A have a profil and Sir B and C doesn't have.
I would like to show a div in my html's page if the selected name doesn't have profil (and already hide if the selected name have a profil). So i create a function to detect if the select name have a value written in my Sheets. If it's correct, i write yes in one div (and no if it's not correct). But when i want to show div, it's doesn't work.
To try to understand my problem, i created a button to launch a function where i get the value of my result. I have undefined each time and i don't know why.
This is my html's code :
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<?!= include('JavaScript'); ?>
<?!= include('StyleSheet'); ?>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
</head>
<body>
<form>
<!-- NAME -->
<div class="form-row">
<div class="form-group col-md-12">
<label for="name"><b>Name :</b></label>
<select class="form-control" id="name" onChange = "showProfil();">
<option disabled selected>Choose ...</option>
<?!=getNames()?>
</select>
</div>
</div>
<!-- RESULT -->
<div><label> Result : </label><p id = "result"></p></div>
<!-- BUTTON -->
<input type="button" class="btn btn-primary btn-block" value="SHOW DIV ?" id = "btnAccesQuestions" onclick = "showDivResultNo();">
<!-- DIV DISPLAY WHEN RESULT IS NO -->
<div id = "divResultNo">
<h2> Result is "NO"</h2>
</div>
</form>
</body>
</html>
This is my server side code :
function doGet() {
return HtmlService.createTemplateFromFile('Index').evaluate().setTitle('Formulaire de demande de formation');
}
function include(filename){
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
function getNames(){
const classeur = SpreadsheetApp.getActiveSpreadsheet();
const feuille = classeur.getSheetByName("Sheet1");
var tNames = feuille.getRange("A2:A").getValues().filter(d =>d[0] !== "").flat();
var names = deleteDuplicateValues(tNames);
return names.map(d => "<option>" + d + "</option>").join("");
}
function deleteDuplicateValues(array) {
var outArray = [];
array.sort(lowerCase);
function lowerCase(a,b){
return a.toLowerCase()>b.toLowerCase() ? 1 : -1;
}
outArray.push(array[0]);
for(var n in array){
if(outArray[outArray.length-1].toLowerCase()!=array[n].toLowerCase()){
outArray.push(array[n]);
}
}
return outArray;
}
function getProfil(name){
const classeur = SpreadsheetApp.getActiveSpreadsheet();
const feuille = classeur.getSheetByName("Sheet1");
var tProfils = feuille.getRange("A2:B").getValues().filter(d =>d[0] !== "");
for (let i = 0; i < tProfils.length; i ++){
if(tProfils[i][0] == name){
if(tProfils[i][1] == ""){
var resultat = "no";
}
else {
var resultat = "yes";
}
}
}
return resultat;
}
function testProfil(){
Logger.log(getProfil("Sir A"));
}
This is my js code :
<script>
function showProfil(){
var name = document.getElementById("name").value;
google.script.run.withSuccessHandler(profil => {
document.getElementById("result").innerHTML = profil;
}).getProfil(name);
}
function showDivResultNo(){
var name = document.getElementById("name").value;
var result = document.getElementById("result").value;
console.log(result)
if (name != "Choose ..." && name != "" && result == "no"){
console.log("show div after that");
}
else {
console.log("div always hidden");
}
}
</script>
And this is a screenshot of my web app after selected Sir A and press button :
If anyone can help me, it would be appreciated. You can acces to my Sheet in this link. Thank you for advance.
In your script, how about the following modification?
From:
var result = document.getElementById("result").value;
To:
var result = document.getElementById("result").innerHTML;
I thought that from your HTML, I thought that the reason of your issue of I have undefined each time and i don't know why. might be due to .value.

Make basic search in array with if and else

I am trying to make a basic search function. if input.value does exist in array alert message, if not, push it to array ans show in HTML. I think I have already most of work done, but there is somewhere a mistake. Thank you in advance for your help guys .)
<div id="main">
<input id="inputForMyDict">
<button id="ButtonForInputSave" onclick="buttonSave()">Speichern</button>
<p id="demo"></p>
</div>
<script>
var myDict = [];
var buttonSave = function() {
for (var i = 0; i < myDict.length; i++) {
if (document.getElementById("inputForMyDict").value = myDict[i]) {
alert("your input is already in your list");
} else {
myDict.push(document.getElementById("inputForMyDict").value);
document.getElementById("demo").innerHTML = myDict;
}
}
}
In javascript, there are 2 ways to do a comparison.
Strict Equality Operator === strict equality operator.
If you are not sure about the exact datatype for the values being compared, then you can use the == for comparison.
The line document.getElementById("inputForMyDict").value = myDict[i] needs comparison operator and not the assignment operator (=). So you need to replace the = with either == or ===.
so your javascript code should look like
var buttonSave = function() {
for (var i = 0; i < myDict.length; i++) {
if (document.getElementById("inputForMyDict").value == myDict[i]) {
// If you know exact data type, then use the below line instead and comment the above line if (document.getElementById("inputForMyDict").value === myDict[i]) {
alert("your input is already in your list");
} else {
myDict.push(document.getElementById("inputForMyDict").value);
document.getElementById("demo").innerHTML = myDict;
}
}
}
Update1: Based on the clarification, provided by comments, you don't need to have a for loop to check for existence of element in array. Javascript provides a convenient way by indexOf method on an array. indexOf method check for the existence of an element in an array and returns the index of the element in the Array. However, if the element is not found then it returns -1.
Full code below which should work.
<!DOCTYPE html>
<html>
<body>
<div id="main">
<input id="inputForMyDict">
<button id="ButtonForInputSave" onclick="buttonSave()">Speichern</button>
<p id="demo"></p>
</div>
<script>
var myDict = [];
var buttonSave = function() {
//for (var i = 0; i < myDict.length; i++) {
var valueInTextbox = document.getElementById("inputForMyDict").value;
if(myDict.indexOf(valueInTextbox) > -1){
alert("your input is already in your list");
} else {
myDict.push(valueInTextbox);
document.getElementById("demo").innerHTML = myDict;
}
}
//}
</script>
</body>
</html>

It works, but sometimes it stops when I click on a button

my code basically works, but when I click the start button a few times, so for example I click on start, the randomnumbers appear, then I type in a number, click on fertig, and make these steps for a few times again. After these few times the start button is "stuck" when I click on it. So I click on it, it goes down, but not up again, you understand ? :-)
Here's the HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Der Einmaleins - Trainer</title>
<link href = "style.css" type = "text/css" rel = "stylesheet">
<script src = "script1m1.js"></script>
</head>
<body>
<h1>Der Einmaleins - Trainer</h1>
<button type="button" onclick = "start();">Start</button>
<button type = "button" onclick = "fertig();">Fertig!</button>
<input id = "erginput" type = "number">
<label id = "rn1"></label>
<label id = "multiplication"></label>
<label id = "rn2"></label>
<br>
<label id = "feedback"></label>
</body>
</html>
Here's the JS:
var randomnumber1;
var randomnumber2;
function start() {
randomnumber1 = getrn();
randomnumber2 = getrn();
while(randomnumber1 == 5 || randomnumber2 == 5 ){
if (randomnumber1 == 5){randomnumber1 = getrn();}
else{randomnumber2 == getrn();}
}
document.getElementById("rn1").innerHTML = randomnumber1;
document.getElementById("multiplication").innerHTML = "x";
document.getElementById("rn2").innerHTML = randomnumber2;
}
function getrn(){
var min = 3;
var max = 10;
var zufallszahl = Math.floor(Math.random() * (max - min)) + min;
return zufallszahl;
}
function ergebnispruefen(zahl,faktor1,faktor2){
var ergebnisrichtig = faktor1 * faktor2;
if (zahl == ergebnisrichtig){
document.getElementById("feedback").innerHTML = "Richtig!";
document.getElementById("feedback").style.color = "Lime";
}else{
document.getElementById("feedback").innerHTML = "Falsch,denk nach!";
document.getElementById("feedback").style.color = "red";
}
}
function fertig(){
var ergebnis = document.getElementById("erginput").value;
ergebnispruefen(ergebnis,randomnumber1,randomnumber2);
}
console.log("Thanks in advance! :-)");
Ji W

How to make a script execute on page load?

I am trying to create a HTML script that will pick a random number out of a list I have given when someone loads the page. This means if they refresh the page a new number will appear. I know how to generate a script that shows a random word/number when you press a button but it is necessary to make the number generate itself and also it can't be in a wordbox. If anyone can help me with this, I'd appreciate it.
I don't know much about coding but from the information I've gathered, here's what I have constructed:
<html>
<head>
<title></title>
<SCRIPT LANGUAGE="JavaScript">
<!--
// Use the following variable to specify
// the number of random words
var NumberOfWords = 32
var words = new BuildArray(NumberOfWords)
// Use the following variables to
// define your random words:
words[1] = "2,719"
words[2] = "2,718"
words[3] = "2,717"
words[4] = "2,715"
words[5] = "2,713"
words[6] = "2,711"
words[7] = "2,710"
words[8] = "2,709"
words[9] = "2,708"
words[10] = "2,706"
words[11] = "2,704"
words[12] = "2,702"
words[13] = "2,701"
words[14] = "2,700"
words[15] = "2,699"
words[16] = "2,698"
words[17] = "2,696"
words[18] = "2,694"
words[19] = "2,692"
words[20] = "2,690"
words[21] = "2,688"
words[22] = "2,686"
words[23] = "2,685"
words[24] = "2,683"
words[25] = "2,681"
words[26] = "2,678"
words[27] = "2,675"
words[28] = "2,673"
words[29] = "2,671"
words[30] = "2,669"
words[31] = "2,667"
words[32] = "2,664"
function BuildArray(size){
this.length = size
for (var i = 1; i <= size; i++){
this[i] = null}
return this
}
document.addEventListener("DOMContentLoaded",
function PickRandomWord(frm) {
// Generate a random number between 1 and NumberOfWords
var rnd = Math.ceil(Math.random() * NumberOfWords)
// Display the word inside the text box
frm.WordBox.value = words[rnd]
})
//-->
</SCRIPT>
<CENTER>
<FORM NAME="WordForm">
<INPUT TYPE=TEXT SIZE=50 NAME="WordBox"><BR>
</CENTER>
</FORM>
<body>
<big><big><span style="font-weight: bold;">
<br>
<br>
<br>
</span></big></big>
</body>
</html>
The problem is it doesn't work and I don't know why.
You should put your script inside the DOMContentLoaded listener:
document.addEventListener("DOMContentLoaded", function() {
//call your script here
});
Note: IE8 does not support addEventListener.
If you are using jquery, you can use $(document).ready
$(document).ready(function() {
//call your script here
});

Razor inside the HTML5

I'm having trouble on putting Razor inside the HTML5.
I can't get the value of id.
I placed the Razor inside the body tag.
This is what it looked like:
#using ThisIsNamespace
#{
VBEncrypt enc = new VBEncrypt();
if(IsPost)
{
if(Request["txtUserID"] != null || Request["txtPassword"] != null)
{
Session["USER"] = Request["txtUserID"];
Session["PASSWORD"] = Request["txtPassword"];
Session["ID"] = enc.Encrypt("" + Session["USER"] + "]#USERID#[" + Session["Password"] + "");
}
}
}
and then assign the Session["ID"] to a variable: this is located in the head tag.
<script type="text/javascript">
var id = #Session["ID"];
</script>
I'm not getting any error but it seems that it fails to assign the session to the variable.
Please let me know if my question is not clear.
Everyones help would be very much appreciated.
Thank you in advance ;)
Simple test:
#{
Session["ID"] = 1;
}
Then:
<script type="text/javascript">
var id = #Session["ID"];
var id2 = #Session["ID2"];
</script>
Renders as:
<script type="text/javascript">
var id = 1;
var id2 = ;
</script>
One of the checks fails. IsPost is false OR Request["txtUserID"] and Request["txtPassword"] are null