variables in javascript - javascript

I have two arrays sd[16][16] and gd[16][16] in javascript. I need to compare the values of the arrays.
var score=0;
document.write("<table>");
for(c1=0; c1<16; c1++)
{ document.write("<tr>");
for(c2=0; c2<16; c2++)
document.write("<td onClick='changeColor(this);'>" + gd[c1][c2] + "</td>");
document.write("</tr>");
}
document.write("</table>");
function changeColor(tdd)
{
if(tdd.bgColor=='white')
{
tdd.bgColor='red';
if (gd[c1][c2] == sd[c1][c2])
score+=5;
else
score-=2;
}
else
{
tdd.bgColor='white';
}
}
However, when I try to display the score later, the score is not displayed.
function scc()
{
document.getElementById('scf').innerHTML = score;
}
</script>
<br><br><center><button type='button' onclick='scc()'> Click to see current score</button> <p id="scf">0</p> </center>
<br><br> <center><input type="submit" value="Get Solution"/></center>
Could someone please tell me what I am doing wrong?

It's a little more work but you could use a closure to keep the score variable isolated.
var score = (function () {
var currentScore = 0;
return {
getScore: function() { return currentScore; },
updateScore: function(change) { currentScore += change; }
}
})()
and then you can get/set the score like this: score.getScore(); and score.updateScore(5); score.updateScore(-4)
This way you don't have to worry about stepping on your score accidentally.

You have forgotten to initialize the score-variable. Now you have the problem your score is only available in the changeColor-function. You can define a score-variable outside all the functions, so that it's available everywhere:
<script type="text/javascript">
var score = 0;
document.write ...
</script>

Related

Is it possible to use a for loop to display values using buttons?

Hello here is my code at the moment. I would like to be able to display "you have selected" and then the name of the player that you pressed the draft button with however when pressing the button then it says you have selected "undefined". Would anyone be able to help thank you very much
var players=["Patrick Mahomes",
"Tyreek Hill",
"Travis Kelce",
"Chris Jones",
"Tom Brady"];
len=players.length;
for (var i=1;
i < len;
i++) {
document.getElementById("draft").innerHTML+=players[i]+"<button type=\"button\" onclick=\"draft()\">Draft</button><br>"
}
function draft() {
document.getElementById("demo").innerHTML+="You have selected"+players[i]+"<br>";
players.splice(players[i]);
}
<p id="draft"></p>
<p id="demo"></p>
the problem is that you don't specify the index when calling draft. You have to call it with the current index. I modified your code for it to work.
It should be easy to understand.
I also changed your var to let as it is better practice in javascript
<script>
let players = ["Patrick Mahomes", "Tyreek Hill", "Travis Kelce", "Chris Jones", "Tom Brady"];
let len = players.length;
for (let i = 0; i < len; i++) {
document.getElementById("draft").innerHTML += players[i] + "<button type='button' onclick='draft("+i+")'>Draft</button><br>"
}
function draft(player) {
document.getElementById("demo").innerHTML += "You have selected " + players[player] + "<br>";
players.splice(players[player]);
}
</script>
yes you can pass the player name as arg for draft()
for (var i=1;i<len;i++) {
document.getElementById("draft").innerHTML+=players[i]+"<button type=\"button\" onclick=\"draft('"+players[i]+"')\">Draft</button><br>"
}
function draft(player){
document.getElementById("demo").innerHTML+="You have selected "+player+"<br>";
players.splice(players[i]);
}
Why not pass i
<!DOCTYPE html>
<html>
<head>
<title>
Draft
</title>
</head>
<body>
<p id="draft"></p>
<script>
var players=["Patrick Mahomes","Tyreek Hill","Travis Kelce","Chris Jones","Tom Brady"];
len=players.length;
for (var i=0;i<len;i++) {
document.getElementById("draft").innerHTML+=players[i]+"<button type=\"button\" onclick=\"draft("+i+")\">Draft</button><br>"
}
// use different variable name for function parameter as var has scope for i here
function draft(k){
document.getElementById("demo").innerHTML+="You have selected"+players[k]+"<br>";
players.splice(players[k]);
}
</script>
<p id="demo"></p>
</body>
</html>
I didn't test but should work. I don't know why you are using players.splice(players[i]); but if you want to remove the element from players use
players.splice(k, 1);
See more https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice#Syntax
Just pass the index to your method draft so you can use it to display the right cell from your array:
var players = ["Patrick Mahomes", "Tyreek Hill", "Travis Kelce", "Chris Jones", "Tom Brady"];
for (var i = 1; i < players.length; i++) {
document.querySelector("#draft").innerHTML += players[i] + "<button type=\"button\" onclick=\"draft("+i+")\">Draft</button><br>"
}
function draft(index) {
document.getElementById("demo").innerHTML += "You have selected " + players[index] + "<br>";
}
<p id="draft"></p>
<p id="demo"></p>
I think you made a typo at declaring the "len" var.
try to use "var len = players.length" or use a comma after the players var declaration.

storing string addition in a variable for calculator function

I am trying to do a Calculator in JavaScript, so I started with addition operation.
I tried to convert addition operator into a string to add into a variable so that I can add the values from function. I found out it is not possible is there any better way to solve this issue.
Codepen
var store = '';
var totalvalue;
function one() {
store += "1";
totalvalue = Number(store);
console.log(totalvalue);
document.querySelector('.exit').textContent = store;
}
function two() {
store += "2";
totalvalue = Number(store)
console.log(totalvalue);
document.querySelector('.exit').textContent = store;
}
function add()
{
store = '+';
totalvalue = parseInt(store);
//THIS IS WHERE ITS NOT WORKING I CAME TO KNOW THAT I CANT STORE A OPERATOR
console.log(totalvalue);
document.querySelector('.exit').textContent = store;
}
function equalsto() {
console.log(totalvalue);
document.querySelector('.total').textContent = totalvalue;
}
<button class="addition" onclick="add()">+</button><br>
<button class="one" onclick="one()">1</button><br>
<button class="two" onclick="two()">2</button><br>
<button class="output" onclick="equalsto()">=</button>
<p class="exit"></p>
<h1 class="total">total</h1>
You're doing it all wrong , in store variable , you should add up the string of all the commands and numbers pressed and use eval to get result whereas you are only replacing store vaiable with current clicked value opreraton like add
You shoudl first add + sign to store and then parse it:
function add()
{
store+ = '+';
totalvalue = parseInt(store);
console.log(totalvalue);
document.querySelector('.exit').textContent = store;
}
A better way would be to design the buttons and get their text in complete string to a final variable.To evaluate result on '=' , you can just use
ans=eval(string_of_variable)
#e {
background-color: red;
}
button:nth-child(4n+2) {
display: block;
}
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<button>5</button>
<button>6</button>
<button>7</button>
<button>8</button>
<button>9</button>
<button>0</button>
<button>+</button>
<button>-</button>
<button>/</button>
<button>*</button>
<p id="e">= (Click to evaluate)</p>
<br>
<p id="ex"></p>
<script>
var main = "";
$("button").click(function() {
main += ($(this)[0].innerText);
$("#ex")[0].innerText = main;
});
$("#e").click(function() {
alert("Answer of " + main + " is: " + eval(main));
main = "";
});
</script>
</html>

JavaScript returning null on a function for a simple guessing game

I created a guessing game using JavaScript. Initially, I wrote it in codepen where it ran fine, and when I moved it over to sublime to test it in the browsers as a standalone, the code did not work. I am getting this error: "Uncaught TypeError: Cannot read property 'value' of null at guess" which is line 14 var guessValue = parseInt(guessIn.value); and links back to the HTML of line 20 which is Guess
I can't figure out where the null is coming from. What am I doing wrong or haven't defined properly that is causing the null? I removed the CSS to blank slate it and make sure that wasn't screwing anything up.
//Generate random number between 1 and 500
var randomNumber = Math.floor((Math.random() * 500) + 1);
//Create variables to store info for loops and displaying info back to user
var guessIn = document.getElementById('userGuess');
var guessOut = document.getElementById('guessesMade');
var counter = 0;
//function runs when the guess button is hit
function guess() {
//declare temp local var and store as an integer for conditional testing
var guessValue = parseInt(guessIn.value);
//if statement for finding the value and reporting to the user
//check if the counter is less than 10 and guessValue is not empty
if (counter < 10 && guessValue) {
counter++;
}
//the guess is correct
if (guessValue == randomNumber) {
guessOut.value = guessOut.value + '\n' + "Guess " + counter + " is " + guessIn.value + ':' + ' You have correctly guessed the number. You may escape.';
}
// the guess is greater
if (guessValue > randomNumber) {
guessOut.value = guessOut.value + '\n' +"Guess " + counter + " is " + guessIn.value + ':' + ' Your guess is incorrect. The number I am thinking of is lower.';
}
//the guess is lower
if (guessValue < randomNumber) {
guessOut.value = guessOut.value + '\n' + "Guess " + counter + " is " + guessIn.value + ':' + ' Your guess is incorrect. The number I am thinking of is higher.';
}
//when all 10 guesses are used
else if (counter == 10) {
guessOut.value = guessOut.value + '\n' + "You did not guess the number I was thinking, " + randomNumber + "." + " You have met your end. Goodbye.";
}
return false;
}
//Show the number to guess upon clicking the checkbox for Cheat
function cheat() {
if (document.getElementById('cheat').checked) { document.getElementById('cheatNumber').value = randomNumber;
document.getElementById('cheatShow').style.display = 'inline';
}
else { document.getElementById('cheatNumber').value = '';
document.getElementById('cheatShow').style.display = 'none';
}
}
//function to reset the game
function reset() {
//reset guess value
userGuess.value = "";
//reset text area
guessesMade.value = "";
//reset counter
counter = 0;
//set new random number for play
randomNumber = Math.floor((Math.random() * 500) + 1);
return false;
}
<html>
<head>
<title>Do You Wanna Play A Game?</title>
<script src="game.js"></script>
</head>
<body>
<h1>Do You Wanna Play A Game?</h1>
<h3>A Guessing Game</h3>
<fieldset>
<legend>The Game Starts Now</legend>
<p>Welcome. You have stumbled upon this page. As a consequence, you have been trapped. To get out, the objective is simple.</p>
<p>I am thinking of a number. This number is between 1 and 500. You get ten guesses.</p>
<p>Good luck.</p>
<div id="guessingarea">
<input type="text" id="userGuess" value="394" /><br />
<button onClick="guess();">Guess</button>
<button onClick="reset();">Reset</button>
<br />
<input id="cheat" type="checkbox" value="cheat" onClick="cheat();" />
<label for="cheat">Cheat</label>
<div id="cheatShow" style="display: none;">
<input id="cheatNumber" type="text"/>
</div>
</div>
</fieldset>
<p></p>
<fieldset>
<legend>Let's examine your guess, shall we?</legend>
<textarea id="guessesMade" rows="14" style="width: 100%;"></textarea>
</fieldset>
</body>
</html>
It looks like you are including the script before your html document.
document.getElementById('userGuess');
is called before the element 'userGuess' exists.
I can think of two solutions to this, either include the script at the end of the document, or access this element only when you need it, rather than declaring it at the beginning like so:
var guessValue = parseInt(document.getElementById('userGuess').value);
You have included the script, before the element is available. As soon as the parser, hits the JS file, it will stop the rendering of the page and try to parse javascript. When the script is encountered, the element is still not available.
You have 2 options to make this work.
Move the script tag to before the close of the body element. This will make sure the page has the available elements before manipulating them.
<fieldset>
<legend>Let's examine your guess, shall we?</legend>
<textarea id="guessesMade" rows="14" style="width: 100%;"></textarea>
</fieldset>
<script src="game.js"></script>
</body>
Query the elements every single time inside the guess method since it is only invoked on a click action, which happens only after page is rendered.
function guess() {
var guessIn = document.getElementById('userGuess');
var guessOut = document.getElementById('guessesMade');
//declare temp local var and store as an integer for conditional testing
var guessValue = parseInt(guessIn.value);
......
......
The reason it works on code pen is because, the scripts are executed are deferred to onLoad which makes sure the elements are available on the page.
If you move the variable declarations inside the function it will work. The issue is that the JavaScript code is executed before the document is ready so the guessIn and guessOut variables are initialised to null.
Alternatively you can wrap your JavaScript code in a function that will execute when the DOM is complete.
document.onreadystatechange = function () {
if (document.readyState === "complete") {
// your code goes in here
}
}
See MDN for more details.

How to make elements appear only when button is clicked in javascript

I'm trying to get answer to display when I press the Show Button but I can't get it to work. Could someone help me understand what I am doing wrong. I can get the first part to work where I generate a random integer. But the second part does not execute (JSFiddle).
<!DOCTYPE html>
<html>
<body>
<button class="button" onclick="disp()">Generate</button>
<button class="button" onclick="show_ans()">Show</button>
<script>
function disp() {
var i = Math.floor((Math.random() * 51) + 1);
var j = 2 * i;
document.getElementById("Goal").innerHTML = [i];
function show_ans() {
document.getElementById("answer").innerHTML = [j];
}
}
</script>
<p> Random Integer:
<span id="Goal"></span>
</p>
<p> Computed Answer:
<span id="answer"></span>
</p>
</body>
</html>
show_ans only exists within the scope of the disp function, so anything outside that scope (such as the rest of the page) can't invoke it.
Move it outside that function:
function disp() {
//...
}
function show_ans() {
//...
}
Of course, since show_ans also relies on j, that too will need to exist in a scope where both functions can access it:
var j;
function disp() {
var i = Math.floor((Math.random() * 51) + 1);
j = 2 * i;
document.getElementById("Goal").innerHTML = [i];
}
function show_ans() {
document.getElementById("answer").innerHTML = [j];
}

JavaScript: Can I declare a variable by querying which function is called? (Newbie)

I'm working with an existing JavaScript-powered cart module that I am trying to modify. I do not know JS and for various reasons need to work with what is already in place.
The text that appears for my quantity box is defined within an existing function:
function writeitems() {
var i;
for (i=0; i<items.length; i++) {
var item=items[i];
var placeholder=document.getElementById("itembuttons" + i);
var s="<p>";
// options, if any
if (item.options) {
s=s+"<select id='options"+i+"'>";
var j;
for (j=0; j<item.options.length; j++) {
s=s+"<option value='"+item.options[j].name+"'>"+item.options[j].name+"</option>";
}
s=s+"</select> ";
}
// add to cart
s=s+"Quantity: <input id='quantity"+i+"' value='1' size='3'/> ";
s=s+"<input type='submit' value='Add to Cart' onclick='addtocart("+i+"); return false;'/></p>";
}
placeholder.innerHTML=s;
}
refreshcart(false);
}
I have two different types of quantity input boxes; one (donations) needs to be prefaced with a dollar sign, and one (items) should be blank.
I've taken the existing additem function, copied it, and renamed it so that there are two identical functions, one for items and one for donations. The additem function is below:
function additem(name,cost,quantityincrement) {
if (!quantityincrement) quantityincrement=1;
var index=items.length;
items[index]=new Object;
items[index].name=name;
items[index].cost=cost;
items[index].quantityincrement=quantityincrement;
document.write("<span id='itembuttons" + index + "'></span>");
return index;
}
Is there a way to declare a global variable based on which function (additem or adddonation) is called so that I can add that into the writeitems function so display or hide the dollar sign as needed? Or is there a better solution?
I can't use HTML in the body of the cart page because of the way it is currently coded, so I'm depending on the JS to take care of it.
Any help for a newbie is welcome. Thanks!
UPDATE 3/22:
Ok, I've edited the .js file as such:
var items=new Array;
var cart=new Array;
var isDonation=false;
function additem(name,cost,quantityincrement) {
var isDonation=false;
if (!quantityincrement) quantityincrement=1;
var index=items.length;
items[index]=new Object;
items[index].name=name;
items[index].cost=cost;
items[index].quantityincrement=quantityincrement;
document.write("<span id='itembuttons" + index + "'></span>");
return index;
}
function adddonation(name,cost,quantityincrement) {
var isDonation=true;
if (!quantityincrement) quantityincrement=1;
var index=items.length;
items[index]=new Object;
items[index].name=name;
items[index].cost=cost;
items[index].quantityincrement=quantityincrement;
document.write("<span id='itembuttons" + index + "'></span>");
return index;
}
...
function writeitems() {
var i;
for (i=0; i<items.length; i++) {
var item=items[i];
var placeholder=document.getElementById("itembuttons" + i);
var s="";
// options, if any
if (item.options) {
s=s+"<select id='options"+i+"'>";
var j;
for (j=0; j<item.options.length; j++) {
s=s+"<option value='"+item.options[j].name+"'>"+item.options[j].name+"</option>";
}
s=s+"</select> ";
}
// add to cart
if (!isDonation) {
s=s+"<input id='quantity"+i+"' size='3' type='hidden'/>";
s=s+"<input type='submit' value='Add to Cart' onclick='addtocart("+i+"); return false;'/><br /><br />";
}
else {
s=s+"$<input id='quantity"+i+"' size='3'/>.00 ";
s=s+"<input type='submit' value='Add to Cart' onclick='addtocart("+i+"); return false;'/><br /><br />";
}
placeholder.innerHTML=s;
}
refreshcart(false);
}
The resulting page isn't differentiating between the additem and adddonation functions is the output. Changing if/else statement to isDonation=true changes all output universally, and isDonation=false changes likewise, but also universally.
I'm at a complete loss.
It's pretty ugly, but you could solve this by having a global variable isDonation. Set this at the beginning of your additem to false, and to true in adddonation. Then in the writeitems function you can check the value and use it to condition your output.

Categories