JS : press enter and go to the next input - javascript

(Sorry if my english is bad)
I try to make a little game where you have to answer question in inputs. When you valid with the key "Enter", next input appear, and a new question in.
It is complicated to explain, so I leave you the test URL : nicolaslorand.com/bac.php
Here is my a part of my code :
var i = 1;
var j = 2;
$('#input'+i).keypress(function(event) {
console.log('input actuel :'+i);
console.log('input suivant :'+j);
if (event.which == 13) {
verification();
console.log("Touche entrée");
}
});
function verification(){
document.getElementById('input'+j).style.display = "block";
var index = $(".inputform").index(this) + 1;
$(".inputform").eq(index).focus();
var recup = document.getElementById('input'+i);
var verif = recup.value.toUpperCase();
var divLettre = document.getElementById('lettre');
var premiereLettre = divLettre.innerText || divLettre.textContent;
if ( verif.charAt( 0 ) === premiereLettre ) {
$("#input"+i).addClass('trueanswer');
i++; j++;
scoreTotal++;
console.log(i);console.log(j);
}
else{
$("#input"+i).addClass('falseanswer');
i++; j++;
console.log(i);console.log(j);
}
With this code, when I press enter, next input appear, but I have to write in the first input so that my answer is verified by the function.

You are using this inside function this refers to window object. i think you should use i instead of this
var index = $(".inputform").index(i) + 1;

Related

Replace window when script ends JavaScript/HTML [duplicate]

This question already has answers here:
Window location replace - timeout help? Javascript question
(2 answers)
Closed 1 year ago.
Is there a way I can insert:
location.replace("https://www.google.com");
After all the functions in my javascript have run, aka when my script ends? I've tried putting it in different parts of my script but it just replaces it straight away.
This is my script currently (sorry it's so long its a text adventure game):
var currentFrame = 0;
var images = document.getElementById("images");
var text = document.getElementById("text");
var buttonBox = document.getElementById('buttonBox');
var input = document.getElementById('input');
//this is the variable for the name of the character
var yerdog;
//this is how after we type in the character name and hit enter
//we will add the name to the variable, remove the input box and start our first scenario
input.onkeypress = function(event) {
console.log(input.value);
if (event.key == "Enter" || event.keyCode == 13) {
yerdog = input.value;
input.parentNode.removeChild(input)
advanceTo(scenario.two)
}
};
//this changes the text and puts in your characters name
var changeText = function(words) {
text.innerHTML = words.replace("Your dog", yerdog);
};
//this takes the image link and puts it in the proper format, sending it to the html
var changeImage = function(img) {
images.style.backgroundImage = "url(" + img + ")";
};
//this looks at the number of options we have set and creates enough buttons
var changeButtons = function(buttonList) {
buttonBox.innerHTML = "";
for (var i = 0; i < buttonList.length; i++) {
buttonBox.innerHTML += "<button onClick="+buttonList[i][1]+">" + buttonList[i][0] + "</button>";
};
};
//this is what moves the game along
var advanceTo = function() {
if (currentFrame >= scenario.length) {
//finish the game code here:
location.replace("https://www.google.com");
}
var s = scenario[currentFrame];
changeImage(s.image)
changeText(s.text)
changeButtons(s.buttons)
};
var scenario = [
one: {
image: "https://s9.postimg.org/eceo9mp73/5860028206_d66810105f_b.jpg", //dog
text: "You have finally decided to take your dog out for a walk. You smile and pat your trusty companion's head. What the dog's name?\n",
},
];
input.onkeypress = function(event) {
console.log(input.value);
if (event.key == "Enter" || event.keyCode == 13) {
yerdog = input.value;
input.parentNode.removeChild(input)
currentFrame = currentFrame + 1; // <--- here
advanceTo() // <-- and here
}
};
//this is the code that starts the game
advanceTo(scenario.one);
You can use ifelse statement as well as timeout for it
setTimeout ( "location()", 5000 );
function location( )
{
location.replace("https://www.google.com");
}
var currentFrame = 0;
var images = document.getElementById("images");
var text = document.getElementById("text");
var buttonBox = document.getElementById('buttonBox');
var input = document.getElementById('input');
//this is the variable for the name of the character
var yerdog;
var scenario = [
{
image: "https://s9.postimg.org/eceo9mp73/5860028206_d66810105f_b.jpg", //dog
text: "You have finally decided to take your dog out for a walk. You smile and pat your trusty companion's head. What the dog's name?\n",
buttons: [],
},
]
//this changes the text and puts in your characters name
var changeText = function(words) {
text.innerHTML = words.replace("Your dog", yerdog);
};
//this takes the image link and puts it in the proper format, sending it to the html
var changeImage = function(img) {
images.style.backgroundImage = "url(" + img + ")";
};
//this looks at the number of options we have set and creates enough buttons
var changeButtons = function(buttonList) {
buttonBox.innerHTML = "";
for (var i = 0; i < buttonList.length; i++) {
buttonBox.innerHTML += "<button onClick="+buttonList[i][1]+">" + buttonList[i][0] + "</button>";
}
};
//this is what moves the game along
var advanceTo = function() {
if (currentFrame >= scenario.length) {
//finish the game code here:
console.log("end of the game");
//location.replace("https://www.google.com"); // uncomment on your page
return;
}
var s = scenario[currentFrame];
changeImage(s.image)
changeText(s.text)
changeButtons(s.buttons)
};
input.onkeypress = function(event) {
console.log(input.value);
if (event.key == "Enter" || event.keyCode == 13) {
yerdog = input.value;
input.parentNode.removeChild(input)
currentFrame = currentFrame + 1; // <--- here
advanceTo() // <-- and here
}
};
//this is the code that starts the game
advanceTo();
<div id="images"></div>
<div id="text"></div>
<div id="buttonBox"></div>
<input type="text" id="input"/>
Based on the code your posted you have 3 important parts:
the advanceTo function
the input.onkeypress event
the scenario list
for that I can suggest one of two changes:
change the scenario to an array (end and call the replace when there is no more elements)
add a end scenario (that calls the replace when it comes to it)
Array approach:
you can change the scenario to an array instead an object:
var scenario = [
{
image: "https://s9.postimg.org/eceo9mp73/5860028206_d66810105f_b.jpg", //dog
text: "You have finally decided to take your dog out for a walk. You smile and pat your trusty companion's head. What the dog's name?\n",
},
{
image: "https://s9.postimg.org/eceo9mp73/5860028206_d66810105f_b.jpg", //dog
text: "You have finally decided to take your dog out for a walk. You smile and pat your trusty companion's head. What the dog's name?\n",
},
]
Also store the current frame in a variable (I suggest at the top of your code):
var currentFrame = 0;
So you can call advanceTo and starting the game (we are not passing the index anymore because is stored in the currentFrame variable:
advanceTo()
and change the logic of the advanced to a little bit:
var advanceTo = function() {
if (currentFrame >= scenario.length) {
//finish the game code here:
location.replace("https://www.google.com");
return;
}
var s = scenario[currentFrame];
changeImage(s.image)
changeText(s.text)
changeButtons(s.buttons)
};
At the end, you need to change your input.onkeypress event:
input.onkeypress = function(event) {
console.log(input.value);
if (event.key == "Enter" || event.keyCode == 13) {
yerdog = input.value;
input.parentNode.removeChild(input)
currentFrame = currentFrame + 1; // <--- here
advanceTo() // <-- and here
}
};

How to add a difficulty to a Javascript hangman game

I want to allow the user to select the difficulty of the game. Easy is words length 3-5, Medium is length 6-9, Hard is 10-15. The word is being pulled from an AJAX API. Also, I've consulted this example but am still struggling to apply it to my own. I included extra code because I'm not sure if I could add radio buttons that store the level and word.length that then updates the word retrieved from the api to be the correct length.
var api = 'https://hangman-api.lively.software';
//add alphabet to div
alphabet.forEach((i) => {
$('.hangman-letters').append(`<div id="letter-${i}">${i}</div>`);
});
//set up initial puzzle
newPuzzle();
//set up new puzzle when user clicks "start over"
$('#game-over-replay').click(function(){
newPuzzle();
});
//trigger game on clicking letter button
$('.hangman-letters div').click(function(){
submitLetter(this.innerHTML, this);
});
//trigger game on keypress
$(window).keypress(function(e){
var thisKey = String.fromCharCode(e.which);
if(alpha.indexOf(thisKey) > -1) {
submitLetter(thisKey, document.getElementById(`letter-${thisKey}`));
}
})
//functions
//handle clicked letter or keyboard input
function submitLetter(letter, thisLetterButton) {
var isCorrect = letterChosen(letter);
if(isCorrect) $(thisLetterButton).addClass('disabled correct');
else $(thisLetterButton).addClass('disabled');
if(remainingBlanks < 1) {
gameOver(true);
}
if(totalIncorrect >= hangmanParts.length + 1) {
gameOver(false);
}
}
//wipe variables and containers and set up new game
//now called after api call is complete
function setUp(){
$('.game-over').hide();
puzzleLetterContainers = [];
previouslyChosen = '';
totalIncorrect = 0;
remainingBlanks = puzzle.length;
$('.hangman-puzzle').html('');
$('#added-parts').html('');
$('.hangman-letters div').each(function(){
this.classList = '';
})
puzzle.split('').forEach((i) => {
var thisClass = "hangman-puzzle-letters",
placeholder = " ";
if(i == ' ' || i == '-') {
thisClass += ' space';
remainingBlanks--;
placeholder = i;
}
$('.hangman-puzzle').append(`<div class="${thisClass}">${placeholder}</div>`);
});
//var difficulty[] = new difficulty;
//var difficulty[1] = Easy;
//var difficulty[2] = Medium;
//var difficulty[3] = Hard;
puzzleLetterContainers = document.getElementsByClassName('hangman-puzzle-letters');
}

Automatic moving Input

I'm trying to have the Input someone puts into the Cell "M19" move to "Z1" and if that Cell is full move it to "Z2" and so on so forth.
Currently my code accurately moves the first and second Input into "M19" into "Z1" and "Z2" but afterwards just stops doing anything.
function myFunction()
{
var ss = SpreadsheetApp.getActiveSheet();
var vZPos = "M19";
var zZPos = "Z1";
var vonZelle = ss.getRange(vZPos); //InputCell
var zuZelle = ss.getRange(zZPos); //FirstOutputCell
var i = 0;
var c = 2;
var cTos = c.toString();
var naechsteZuZelle = zZPos.replace("1", cTos);
var naechsteZuZelleRange = ss.getRange(naechsteZuZelle); //ChangingOutputCell
do
{
if (zuZelle.isBlank() == true && c == 2)
{
vonZelle.moveTo(zuZelle);
i++;
}
else
{
if (naechsteZuZelleRange.isBlank() == true)
{
vonZelle.moveTo(naechsteZuZelleRange);
i++;
}
else
{
c++;
}
}
}
while (i == 0);
}
Since I'm not that skilled at coding I've kinda hit a brick wall on how to go on about doing things, I would aprreciate any help and/or explanations on how to solve my Problem.
P.S. Since I'm coding in German some of the Variable names might seem weird, if there are any questions I'll do my best to translate/elaborate on them.
Change:
else
{
c++;
}
To:
else
{
c++;
cTos = c.toString();
var naechsteZuZelle = zZPos.replace("1", cTos);
var naechsteZuZelleRange = ss.getRange(naechsteZuZelle)
}
It was not in your loop.

Getting an infinite loop and can't see why - Javascript

I'm writing a simple little Connect 4 game and I'm running into an infinite loop on one of my functions:
var reds = 0;
var greens = 0;
function checkEmpty(div) {
var empty = false;
var clicked = $(div).attr('id');
console.log(clicked);
var idnum = parseInt(clicked.substr(6));
while (idnum < 43) {
idnum = idnum + 7;
}
console.log("idnum=" + idnum);
while (empty == false) {
for (var i = idnum; i > 0; i - 7) {
idnumStr = idnum.toString();
var checking = $('#square' + idnumStr);
var str = checking.attr('class');
empty = str.includes('empty');
console.log(empty);
var divToFill = checking;
}
}
return divToFill;
}
function addDisc(div) {
if (reds > greens) {
$(div).addClass('green');
greens++;
console.log("greens=" + greens);
} else {
$(div).addClass('red');
reds++;
console.log("reds=" + reds);
};
$(div).removeClass('empty');
}
$(function() {
var i = 1;
//add a numbered id to every game square
$('.game-square').each(function() {
$(this).attr('id', 'square' + i);
i++;
//add an on click event handler to every game square
//onclick functions
$(this).on('click', function() {
var divToFill = checkEmpty(this);
addDisc(divToFill);
})
})
})
Here is a link to the codepen http://codepen.io/Gobias___/pen/xOwNOd
If you click on one of the circles and watch the browser's console, you'll see that it returns true over 3000 times. I can't figure out what I've done that makes it do that. I want the code to stop as soon as it returns empty = true. empty starts out false because I only want the code to run on divs that do not already have class .green or .red.
Where am I going wrong here?
for (var i = idnum; i > 0; i - 7);
You do not change the i.
Do you want to decrement it by 7?
Change your for loop to the one shown below:
for (var i = idnum; i > 0; i -= 7) {
// ...
}
You also do not use loop variable in the loop body. Instead, you use idnum, I think this can be issue.
while (empty == false) {
for (var i = idnum; i > 0; i -= 7) {
idnumStr = i.toString(); // changed to i
var checking = $('#square' + idnumStr);
var str = checking.attr('class');
empty = str.includes('empty');
console.log(empty);
var divToFill = checking;
// and don't forget to stop, when found empty
if (empty) break;
}
}
I add break if empty found, because if we go to next iteration we will override empty variable with smallest i related value.
You can also wrap empty assignment with if (!empty) {empty = ...;} to prevent this override, but I assume you can just break, because:
I want the code to stop as soon as it returns empty = true
Offtop hint:
while (idnum < 43) {
idnum = idnum + 7;
}
can be easy replaced with: idnum = 42 + (idnum%7 || 7)
Change to this:
for (var i = idnum; i > 0; i = i - 7) {
You are not decrementing the i in your for loop
Building on what the others have posted You would want to change the value of empty inside the for loop. because obviously the string still checks the last string in the loop which would always return false.
while(empty==false){
for (var i = idnum; i > 0; i -= 7) {
// your other codes
if (!empty) {
empty = str.includes('empty');
}
}

keeping a innerhtml value from a javascript after a html form submit

I am using below javascript to collect values from some textboxes,do some calculations and display the result as a innerhtml content
window.onload = function () {
var left = document.getElementById('mem_count');
var right = document.getElementById('siz_single');
var result = document.getElementById("disp_siz");
function check(a, b, elem) {
var txt = '';
if (a === 0 && b === 0) {
}
else if (a !== 0 && b === 0) {
txt = "Enter size of single device in above column"
}
else if(a == 0 && b !== 0){
txt = "Enter Meta member count in above column "
}
else {
var c = 1 +a
txt = "Your meta device size is " + (c*b) +" MB" + " = " + (c*b/1024) +" GB ";
}
disp_siz.innerHTML = txt;
}
mem_count.onkeyup = calc;
siz_single.onkeyup = calc;
function calc() {
var a = parseFloat(mem_count.value) || 0;
var b = parseFloat(siz_single.value) || 0;
check(a,b, this);
}
}
and the output will be display in between the div
<div id="disp_siz"><-----above output will come here----></div>
This div is part of a html form. I am able to keep all my other form values in same field after form submission. But not able to display above output. It just clearing my values. Is there anyway I can echo this javascript variable value to the same field after form submision ?
First Option:
Set it on the serverside.
Second Option:
If the page refreshes, it is like cleaning a whiteboard, you got to start over. If the fields are there, trigger the function to run.
Add calc(); to the end of the onload function.
...
...
function calc() {
var a = parseFloat(mem_count.value) || 0;
var b = parseFloat(siz_single.value) || 0;
check(a,b, this);
}
calc(); //<-- added this to trigger the calculation
}
Another problem:
And you should not reference an element by their id directly. You should use
document.getElementById("disp_siz").innerHTML = txt;
You're referencing a variable (disp-siz) that doesn't exist. Use the variable you created earlier, result.
result.innerHTML = txt;

Categories

Resources