Function will not execute more then once - javascript

I am trying to make a hangman game with an on-screen keyboard, there is alot more code then this but this is the specfic function that won't run. The HTML is just an example of one key, there are 27 including a space, all of them only run the wrong() function once.
Here's the HTML that executes the function:
<p class="key" id="q" onclick="q(); setTimeout(allclick, 200); setTimeout(wrong, 1000);" onmouseover="hoverq()" onmouseout="unhoverq()">Q</p>
And the script that should fire off everytime one of the keys is pressed but it doesn't.
<script>
function wrong(){
console.log("wrong()")
console.log(clickon)
if(wrong == length){
console.log("all wrong")
document.getElementById(clickon).setAttribute("onmouseover", " ")
document.getElementById(clickon).setAttribute("onmouseout", " ")
document.getElementById(clickon).setAttribute("onclick", " ")
document.getElementById(clickon).style.backgroundColor="red"
}else{
wrongcheck = 1
console.log(wrongcheck)
}
console.log("_____")
</script>
Edit:
This may help you understand this better.
var length = word.length;
function allclick(){
for(l = 0; l <= length; l++){
if(clickon == letter[l]){
if(clickon == " "){
document.getElementById("blank" + l).innerHTML = " "
document.getElementById("space").setAttribute("onmouseover", "")
document.getElementById("space").setAttribute("onmouseout", "")
document.getElementById("space").setAttribute("onclick", "")
document.getElementById("space").style.backgroundColor="green"
document.getElementById("blank" + l).style.margin = "5px 50px"
}else{
console.log("correct")
document.getElementById("blank" + l).innerHTML = clickon + "&nbsp"
document.getElementById(clickon).setAttribute("onmouseover", "")
document.getElementById(clickon).setAttribute("onmouseout", "")
document.getElementById(clickon).setAttribute("onclick", "")
document.getElementById(clickon).style.backgroundColor="green"
}
}else if(clickon != letter[l]){
wrong = wrongcheck++
}
}
console.log("_____")
}
if you want I can send you the entire thing.

Related

Displaying buttons and printing a variable in javascript

I'm fairly new to JavaScript, but I have some experience in other languages. I've been working on making my own small project, and I'm still figuring out how some things work. I have two problems that I need help solving. The first one, is that I have a button that should appear after you get 100 points, and click the button. This is at the if (buyupgrade == 1) and the following parts of that. I want the button to appear after the conditions are met (buy the first upgrade after getting 100 points). I also want to be printing the text part of a button, but in the text, I need it to display a variable, So my button text will display some words and a variable. Thanks for the help!
<!DOCTYPE html>
<html>
<body>
<p>Click to get started!</p>
<button onclick="addPoints()">Add points</button>
<button id="btn_multiply" onclick="firstx2()" style="display:none;">x2 Multiplier. Cost: 100</button>
<button id="firstbuild" onclick="build1()" style="display:none;">Building 1. Cost 200</button>
<script>
var points = 98;
var pointMulti = 1;
var buyupgrade = 0;
var currentpoints = setInterval(pointupdate, 1000);
function addPoints() {
points += pointMulti;
var pointsArea = document.getElementById("pointdisplay");
pointsArea.innerHTML = "You have " + points + " points!";
if(points >= 100 && buyupgrade == 0) {
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "inline";
}
}
function firstx2() {
if (buyupgrade == 0) {
pointMulti *= 2;
buyupgrade++;
points -= 100;
var multiplierArea = document.getElementById("multidisplay");
multiplierArea.innerHTML = "Your multiplier is: " + pointMulti + "!";
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "none";
}
}
if (buyupgrade == 1) {
document.getElementById("firstbuild");
firstbuild.style.display = "inline";
function build1() {
}
}
function pointupdate() {
document.getElementById("pointdisplay").innerHTML = "You have " + points + " points!";
}
</script>
<p id="pointdisplay"></p>
<p id="multidisplay"></p>
</body>
</html>
Your code that is supposed to make the third button visible is by itself outside any function. This seems like a typo:
if (buyupgrade == 1) {
document.getElementById("firstbuild");
firstbuild.style.display = "inline";
function build1() {
}
This only gets called the first time through the program when buyupgrade == 0
I think you meant for this to be inside the function:
function firstx2() {
if (buyupgrade == 0) {
pointMulti *= 2;
buyupgrade++;
points -= 100;
var multiplierArea = document.getElementById("multidisplay");
multiplierArea.innerHTML = "Your multiplier is: " + pointMulti + "!";
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "none";
}
if (buyupgrade == 1) {
var firstbuild = document.getElementById("firstbuild");
firstbuild.style.display = "inline";
// add some text to the button
firstbuild.innerText = "buyupgrade: " + buyupgrade
}
}
Also, there's a typo:
document.getElementById("firstbuild");
should probably be:
var firstbuild = document.getElementById("firstbuild");

How do I use inner.HTML in a function?

I tried to create a Html / Js money counter but if i update, it updates one tick and then it resets itself to an old value. I tried creating a function named update and let it run every time the money value changes, but that did not work either.
<html>
<head>
<title>Betting Simulator Test!</title>
</head>
<body>
<br/>
<p id="p1">You have 500$</p>
<br/>
<form name="CoinFlip" action="" onsubmit="Create()" method="post">
Coins: <input type="text" name="Csubmit">
<input type="submit" value="Flip the Coin">
</form>
<script type="text/javascript">
Balance = 500;
function Game() {
if(Balance >= 1) {
var Coin = confirm("You have put " + sub + "$ in the CoinFlip!");
if(Coin == true) {
var flip = true
if(flip == true) {
alert("You won " + sub + "$");
Balance = Balance + sub*2 - sub;
Update = document.getElementById("p1").textContent="You have " + Balance + "$";
} else {
alert("You lost " + sub + "$");
Balance = Balance - sub;
Update = document.getElementById("p1").textContent="You have " + Balance + "$";
}
} else {
}
} else {
alert("You ran out of Money");
}
}
function Create() {
sub = document.forms["CoinFlip"]["Csubmit"].value;
if(sub <= Balance && sub > 0) {
Game();
} else {
alert("value does not make any sense!");
}
}
</script>
</body>
You have multiple problems. The first one is that you submit a form each time you play, so the page refreshes, and everything is lost. You could find a workaround to avoid this (see this), but in this case, a form is really not needed.
Also, the user is always going to win because you always set flip to true. You can simulate a random win by using this snippet:
var win = Math.round( Math.random() ); // 1 or 0 (truthy or falsy)
Here is a working example:
var balance = 500;
document.getElementById('flip').addEventListener('click', play);
function play(){
// parseInt() converts a String to an integer (10 is for decimal base)
var bet = parseInt(document.getElementById('bet').value, 10);
if(bet <= balance && bet > 0)
{
var accepted = confirm("Do you really want to bet " + bet + "$?");
if(accepted)
{
var win = Math.round( Math.random() ); // Random win
if(win)
{
alert("You won " + bet + "$!");
balance += bet;
}
else
{
alert("You lost " + bet + "$...");
balance -= bet;
}
if(!balance){ alert('You ran out of money...'); }
document.getElementById('p1').textContent = "You have " + balance + "$";
}
document.getElementById('bet').value = 0;
}
else
{
alert("Your bet makes no sense!");
}
}
<p id="p1">You have 500$</p>
<p>Coins: <input type="number" value="0" id="bet"> <button id="flip">Flip the coin</button>

Alert returning more than once

I'm learning JS and I'm trying to solve a coding challenge. I'm suppose to have an alert tell the user the total generator amount and the total watts when I input the parameters. Problem is the code reader says that I'm alerting more than one. What am I doing that is making the alert be called multiple times? Here was my first attempt:
function changePowerTotal(totalMW,genID,status,powerMW){
if(typeof(status) == "on" || typeof(status) == "ON"){
alert("Generator #"+genID+" is now on, adding "+powerMW+" MW, for a total of "+ (totalMW) +" MW!");
return false;
} else {
if(totalMW == 0){
alert("Generator #"+genID+" is now off, removing "+powerMW+" MW, for a total of "+ (powerMW) +" MW!");
} else {
alert("Generator #"+genID+" is now off, removing "+powerMW+" MW, for a total of "+ (totalMW - powerMW) +" MW!");
}
return false;
}
}
changePowerTotal(0,2,"off",62);
I've also tried this:
function changePowerTotal(totalMW,genID,status,powerMW){
var genStatus = "";
if(status === "on"){
genStatus = " is now on, adding "
totalMW = totalMW + powerMW;
} else {
genStatus = " is now off, removing "
totalMW = totalMW - powerMW;
}
alert("Generator #"+genID+genStatus+powerMW+" for a total of "+totalMW+" MW!");
}
changePowerTotal(142,2,"off",62);
There is no problem in the function, I am guessing you per accidentally called it twice?
Please check if you did, there is no way this functions can alert twice. You must have made a mistake in calling it twice.
Thank you all for the help. I found the solution, here it is:
function changePowerTotal (totalMW, genID, genStatus,genMW){
var curStatus = " ";
var sumMW = 0;
if(genStatus === "off"){
curStatus = " is now "+genStatus+", removing ";
alert("Generator #"+genID+curStatus+genMW+" MW, for a total of "+totalMW+"MW!");
return totalMW + genMW
} else {
curStatus = " is now "+genStatus+", adding ";
sumMW = genMW + totalMW;
alert("Generator #"+genID+curStatus+genMW+" MW, for a total of "+(totalMW + genMW)+"MW!");
return totalMW + genMW
}
}

Cant figure out why my div output isn't working

I have a basic hangman program. Click on the letter, it then tells you if its right or wrong by coloring the letter red or green. If its green, it replaces a dash in the hidden word with the letter. That part of my code works. The part that doesn't work is that I have an output section to a div that is supposed to tell you if you got the guess correct or not, and upon 6 failed guesses, you lose and it resets. It's currently not doing any of that. It's not even displaying anything in the div at all.
TY ahead of time. If you have questions about something I didn't explain well enough, ill be back in about 1 hour to answer them. Thanks!
Jsfiddle - http://jsfiddle.net/25b3fr4u/
HTML -
<body>
<form id="form" name="form" method="post" action="">
<input type="button" id="but" value="Start"/>
<div id="hangman-jquery">
<div id="word"></div>
<div id="alpha"></div>
</div>
</form>
<div id="win">
</div>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="hangman.js"></script>
</body>
JS -
function hangman(word) {
var trys = 0;
var guess = 0;
var alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$.each(alpha.split(''), function(i, val) {
$('#alpha').append($('<span class="guess">' + val + '</span>'));
});
$.each(word.split(''), function(i, val) {
$('#word').append($('<span class="letter" letter="' + val + '">-</span>'));
});
$('.guess').click(function() {
var count = $('#word [letter=' + $(this).text() + ']').each(function() {
$(this).text($(this).attr('letter'));
}).length;
$(this).removeClass('guess').css('color', (count > 0 ? 'green' : 'red')).unbind('click');
if (guess > 0) {
$('#win').text("Correct Guess");
} else if (guess < 0) {
$(this).html(++trys);
$('#win').text("You have tried to guess the word and failed " + trys + " times");
}
if (trys == 6) {
alert("You have guessed six times, you lose");
trys = 0;
$("#win").text("");
}
});
}
$(document).ready(function() {
$('#but').click(function() {
var options = new Array("DOG", "CAT", "BAT", "HORSE", "TIGER", "LION", "BEAR", "LIGER", "DOOM", "SPIDER", "TREES", "LAPTOP");
var random = 1 + Math.floor(Math.random() * 12);
hangman(options[random]);
});
});
Code fixed :http://jsfiddle.net/25b3fr4u/1/. The trys where not incremeted properly and you have to check the count instead of guess in your condition. guess was set to 0 and never use.
var count = $('#word [letter=' + $(this).text() + ']').each(function() {
$(this).text($(this).attr('letter'));
}).length;
$(this).removeClass('guess').css('color', (count > 0 ? 'green' : 'red')).unbind('click');
if (count > 0) {
$('#win').text("Correct Guess");
} else if (!count > 0) {
trys++;
$('#win').text("You have tried to guess the word and failed " + trys + " times");
}
if (trys == 6) {
alert("You have guessed six times, you lose");
trys = 0;
$("#win").text("");
}
I'm sure you can handle the rest. Have fun.

validation only working if all text inputs are blank, not any text input is blank

I want to produce a validation message in an alert for when any text input within a question is empty. So for example if I have 2 blank text inputs for question 1, if both text inputs are blank, it displays the validation message You have not entered in a value in all the Indivdiaul Marks textbox.
But the problem is that for question 1 for example, if 1 text input is blank but the other is not blank, it does not display the validation message, even though it should do as not all text inputs have been filled for question 1.
My question is that how can I get the validation message to appear if there is any blank text input per question?
Here is a fiddle so you can test it: http://jsfiddle.net/cbyJD/87/
Below is the validation() function code:
function validation() {
// only keeping track of the final message
var alertValidation = "",
// toggle for showing only one error
showOnlyOneError = true;
$("input[data-type='qmark']").each(function(i) {
var questions = $(this).attr("data-qnum");
var marks = parseInt($("[class*=q" + (i+1) + "_ans_text]").text());
var txtinput = $(this).val();
// the message for this question
var msg = '';
if (txtinput == '') {
msg += "\n\u2022 You have not entered in a value in all the Indivdiaul Marks textbox \n";
}
if (marks < 0) {
msg += "\n\u2022 Your Total Marks Remaining does not equal 0 \n - You Need To Remove " + Math.abs(marks) + " Marks";
} else if (marks > 0) {
msg += "\n\u2022 Your Total Marks Remaining does not equal 0 \n - You Have " + marks + " Marks Remaining";
}
// if there is an error for the question, add it to the main message
if (msg.length) {
alertValidation += alertValidation.length ? '\n\n' : '';
alertValidation += "You have errors on Question Number: " + questions + "\n";
alertValidation += msg;
// stop if we only care about the first error
return !showOnlyOneError;
}
});
// show the error messages
if (alertValidation != "") {
alert(alertValidation);
return false;
}
return true;
}
First, add a hidden variable num_groups with the total number of groups.
<p>
<input type='hidden' id='num_groups' name='num_groups' value='2'>
<input id="submitBtn" name="submitMarks" type="submit" value="Submit Marks" />
</p>
Second, change the validate function to work on a single group of questions:
function validation(group) {
var msg = [];
var nb = 0; // Number of blank values
$("input[data-qnum='" + group + "']").each(function() {
if ($(this).val() == '') {
nb++;
return false;
}
});
if (nb != 0) {
msg.push("\u2022 You have not entered in a value in all the Individual Marks textbox");
}
var marks = parseInt($("[class*=q" + group + "_ans_text]").text());
if (marks != 0) {
msg.push("\u2022 Your Total Marks Remaining does not equal 0");
if (marks < 0) {
msg.push("- You Need To Remove " + -marks + " Marks");
} else if (marks > 0) {
msg.push("- You Have " + marks + " Marks Remaining");
}
}
if (msg.length > 0) {
alert("You have errors on Question Number: " + group + "\n\n" + msg.join("\n"));
return false;
} else {
return true;
}
}
Third, change the myClickhandler function to validate all the groups:
myClickHandler = function(e) {
var ng = $('#num_groups').val();
for (var group = 1; group <= ng; group++) {
if (!validation(group)) return false;
}
if (confirm("Are you sure you want to Proceed?")) {
$.ajax({
url: "insertmarks.php",
data: $("#markstbl").serialize(),
async: false,
type: "POST"
});
return true;
} else {
return false;
}
}
JsFiddle here.
The validation() function returns true no matter what it finds.
You need to declare a variable at the top of this function called errors or similar, with a value of false. For everywhere in the function that an error is found, set the value of errors to true.
At the close of the function with...
return !errors; // return the value of errors NOT'ed
Then you call call validation() in a test, like so...
if (validation()) {
// everything is groovy
} else {
// make them do the form over, or something
}

Categories