If statements JavaScript, maths will not work in my else statement what am I doing wrong? [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
This question is pretty straightforward. I am making a number guessing game and I am now adding an attempts function to my game. Every failed attempt should add 1 to my attempts variable:
var numberwang = Math.floor(Math.random() * 6);
var attempts = 0;
console.log(numberwang);
console.log(attempts);
document.getElementById("guessbutton").onclick = function(e) {
e.preventDefault();
if (document.getElementById("guess").value == numberwang) {
alert("That's numberwang!");
attempts = 0;
console.log("Attempts:",attempts)
} else {
alert("That's not numberwang, try again");
attempts = attempts + 1;
console.log("Attempts:",attempts)
}
}
<p>Guess a number</p>
<form><input type="text" id="guess"><button id="guessbutton">Guess</button></form>
However the else statement argument doesn't work. Each attempt does not add anything to my attempts variable. Can anyone see what is wrong? Thanks in advance.
Note: the else statement is not working for anything mathematical.

You are defining a variable everytime you click.
Removing the "var" from inside the if/else block
<p>Guess a number</p>
<form><input type="text" id="guess"><button id="guessbutton">Guess</button></form>
<script type="text/javascript">
var numberwang = Math.floor(Math.random() * 6);
var attempts = 0;
console.log(numberwang);
console.log(attempts);
document.getElementById("guessbutton").onclick = function(e) {
e.preventDefault();
if (document.getElementById("guess").value == numberwang) {
alert("That's numberwang!");
attempts = 0;
} else {
alert("That's not numberwang, try again");
attempts = attempts + 1;
}
}
</script>

Your problem is that when you use the var keyword, you are making a new variable. You should remove the var inside both the if and the else. This will let you change the outer attempts variable, and not the new one that you define by using the var.
var numberwang = Math.floor(Math.random() * 6);
var attempts = 0;
document.getElementById("guessbutton").onclick = function(e) {
e.preventDefault();
if (document.getElementById("guess").value == numberwang) {
alert("That's numberwang!");
attempts = 0;
} else {
alert("That's not numberwang, try again");
attempts = attempts + 1;
}
console.log("Attempts is: "+attempts);
}
<p>Guess a number</p>
<form><input type="text" id="guess"><button id="guessbutton">Guess</button></form>
I think that I understand what you are having a problem with. You expect what is already logged to the console to change when the variable changes. That's not how console.log works. It only logs the current value of the variable. If you want to see the new value, you should log it again, in this case after each guess is made.

Related

javascript game help pls [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
The game is able to get unlimited money by pressing the button. How do I prevent this?
var workbard = document.getElementById("workbar");
function work() {
var zaman = setInterval(function () {
workbard.value +=1;
if (workbard.value == 10) {
workbard.value -=11;
workbard.style.visibility = 'hidden'
clearInterval(zaman);
money = money +=5;
experience = experience +=10;
document.getElementById("para").innerHTML= ":" +money;
document.getElementById("exp").innerHTML=":" +experience;
}
<progress id="workbar" alue="0" max="10"></progress>
<button type ="button"id="workb2"onclick="work(),document.getElementById('workbar').style.visibility='visible'">Work</button>
you need to initialize some variables, add a limit and then use an if statement
var workbard = document.getElementById("workbar");
var money = 0;
var experience=0;
var limit = 30;
function work() {
var zaman = setInterval(function () {
workbard.value +=1;
if (workbard.value == 10) {
workbard.value -=11;
workbard.style.visibility = 'hidden'
clearInterval(zaman);
money = money +=5;
if(money > limit)money = limit;
experience = experience +=10;
document.getElementById("para").innerHTML= ":" +money;
document.getElementById("exp").innerHTML=":" +experience;
}})}
<progress id="workbar" alue="0" max="10"></progress>
<button type ="button"id="workb2"onclick="work(),document.getElementById('workbar').style.visibility='visible'">Work</button>
<div id='para'></div>
<div id='exp'></div>

Creating a new line for an output using the same variable?

Very much a newbie here and wanting a bit of guidance.
I'm trying to create a project where you bind a key to start a timer then show an output in the results box. However i'm facing an issue where I need to create a new line if the user releases the bound button to start a new timer, however I can't find a way to start the timer again. Bear in mind within the time, a user could press the bound key over a hundred times, I don't want to manually create new lines and timer's.
My thoughts are creating a a random token, then on release, it creates a break, if the next line doesn't match this token it begins again.
Edit:So you can see, the value is based on the 2 variables, and even when I hold down the specific button again, it just adds to the current smallTime. I know this is how it's currently build, but i'm trying to get it to reset and go to the next line dynamically.
Any help would be greatly appreciated.
<html>
<head>
<textarea class="code_input" name="allInputs" id="textareaCode" wrap="logical" rows="10" cols="50" readonly="true"> </textarea>
<script type="text/javascript">
var shortSeconds = 0;
var shortmillisec = 0;
function buttonPressed(e) {
key = String.fromCharCode(e.keyCode).toLocaleLowerCase()
//alert (key)
keyInput = e.keyCode
if (withinTime == true && key == bind) {
shortDisplay()
shortTimerFunction();
}
}
function shortDisplay() {
if (shortmillisec >= 9) {
shortmillisec = 0
shortSeconds += 1
}
else
shortmillisec += 1
}
function startstoptimerShort() {
if (shortTimer > 0) {
clearTimeout(shortTimer);
shortTimer = 0;
} else {
withinTime = true
shortTimerFunction()
}
}
function shortTimerFunction() {
smallTime = shortSeconds + "." + shortmillisec;
shortTimer = setTimeout("shortTimerFunction()", 100);
//need to work out what line to put the output on
allInputs = document.getElementById('textareaCode')
allInputs.value = (textbox3.value) + (": " + smallTime) + '\n';
}
</script>
</body>
</html>

syntax issues with js/jquery assignment - Quiz questions in an object

I'm trying to work through an assignment to further my understanding of js but I'm running into some issues that are keeping me from final code. The code executes a short quiz- inputs from radio buttons are taken in and matched to an object containing answers, then outputting a final score.
code at http://jsfiddle.net/8ax9A/3/
issues I'm aware of now :
my $response variable doesn't seem to work.
var $response = $('[name=rad]:checked').val();
counter is listening for clicks through questions. After the last question, I want to report final score. I can't get counter to reach the end of questions + 1, and I cant get an accurate final score listener reported (var finalScore).
if ($response == parseInt(questions[counter].answer, 10)) {
finalScore++;
}
Those are just snippets so check out the fiddle for full code. I'd love some suggestions on how to understand where I'm going wrong.
Here is one way you could do it:
//Initialization
var counter=0;
var score=0;
loadQuestion();
$('#next').on('click',answer);
//functions
function answer(){
// if the user did not answer
if ($('input:radio:checked').length == 0){
alert('You have to answer!');
return;
}
var currentQ=questions[counter];
// if answer is correct
if($('[name=rad]:checked').val()==currentQ.answer){score++;}
counter++;
// if there are no questions left
if(counter >= questions.length) {displayResults(); return;}
loadQuestion();
}
function loadQuestion(){
// clear the radio buttons
$("input:checked").removeAttr("checked");
var currentQ=questions[counter];
// display the question
$('h1').text(currentQ.question);
$('#a1').text(currentQ.choices[0]);
$('#a2').text(currentQ.choices[1]);
$('#a3').text(currentQ.choices[2]);
}
function displayResults(){
$("h1").text("You've finished with a score of " + score + "!");
$('[name=rad], #a1, #a2, #a3, #next').remove();
}
JS Fiddle

why is this if statement not doing anything? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Believe me the HTML won't be necessary on this one since the if statement only deals with the cBox variable. What this does is, create or close a div upon clicking a button, i've tested the functions and they work, what's not working however is the way these functions are called, I've logged the outputs but i get neither of them displayed in the console, this means the code is not running through the if statement for some reason.
Also tried with if (cBox == null) and it doesn't work ...
btnPress.onclick = function formConfirm() {
var cBox = document.getElementById('cBox');
console.log(" but cbox is "+cBox);
if(cBox) {
closecBox();
console.log("cbox exists, closing ...");
} else {
opencBox();
console.log("cbox does not exist, creating...");
}
};
I am not sure i understand your question but if your code is like this seems to work fiddle
function closeBox(elem){
elem.parentNode.removeChild(elem);
}
function openBox(el){
var el = document.createElement('div');
el.setAttribute("id", "cBox");
document.body.appendChild(el);
}
var btnPress = document.getElementById('button');
btnPress.onclick = function formConfirm() {
var cBox = document.getElementById('cBox');
if(cBox) {
closeBox(cBox)
console.log("cbox exists, closing ...");
} else {
openBox(cBox);
console.log("cbox does not exist, creating...");
}
};
If i did not understand your question sorry for having done wasting time.
Guys thank you for all the replies, your hints were definitely helpful for solving this problem, i made so many changes that i lost track but this is the working code
var btnPress = document.getElementById('theBtn');
btnPress.onclick = function formConfirm() {
var cBox = document.getElementById('confirmBox');
console.log("cbox is "+cBox);
if(cBox) {
console.log("cbox exists, closing ...");
closecBox();
} else {
opencBox();
console.log("cbox does not exist, creating...");
}
};
function opencBox() {
var cBox = document.createElement('div');
cBox.id = "confirmBox";
document.body.appendChild(cBox);
cBox.style.display="inline";
};
function closecBox() {
var cBox = document.getElementById('confirmBox');
cBox.style.display="none";
document.body.removeChild(cBox);
};
I also used display style to test some other stuff with animations :) once again, thank you so much for all the comments! They really helped me out figuring the solution!

If a checkbox is checked or unchecked - code optimization - jquery [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
So I have a jquery "checkbox checked/unchecked" function working well. This is a checkbox for turning on or off a particular URL parameter - BUT I believe this code could be written a lot tighter. Does anyone have any suggestions?
$('#mapControl').live('click', function(){
var thisUrl = $(location).attr('href');
if($(this).is(':checked')) {
var lastFour = thisUrl.substr(thisUrl.length - 4);
var param;
if (lastFour == 'com/') {param='?mapControl=true'} else {param='&mapControl=true'}
thisUrl=thisUrl+param;
} else {
$('#urlParam').val(thisUrl);
if (thisUrl.indexOf('?mapControl=true') >= 0){
thisUrl=thisUrl.replace('?mapControl=true','');
} else if (thisUrl.indexOf('&mapControl=true') >= 0){
thisUrl=thisUrl.replace('&mapControl=true','');
}
}
$('#urlParam').val(thisUrl);
});
Try to avoid jQuery as much as you can for example
$('#mapControl').live('click', function(){
// you can directly read window location href attribute
var thisUrl = window.location.href;
var urlParamObj = $('#urlParam');
// instead of $(this).is(':checked') YOU can write *this.checked === true*
if(this.checked === true) {
var lastFour = thisUrl.substr(thisUrl.length - 4);
var param;
if (lastFour == 'com/') {param='?mapControl=true'} else {param='&mapControl=true'}
thisUrl=thisUrl+param;
} else {
urlParamObj.val(thisUrl);
/* if you are sure that your location may have "?mapControl=true" OR "&mapControl=true"you don't have to write code to check string directly replace
*/
thisUrl=thisUrl.replace('?mapControl=true','');
thisUrl=thisUrl.replace('&mapControl=true','');
}
// you don't have to write $('#urlParam') 2 times create a object and refer it again and again
urlParamObj.val(thisUrl);
});

Categories