Morgan Clarke Morgan Clarke - 5 months ago 8x
HTML Question

Incorrect result from element value comparison

I'm making an

card game and it has an
statement with a greater than or equal to comparison operator. But when the money is lower that the price it still runs as if you have the needed money.


<article id="moneysys">
<p id="ptdabtd" >Click 'Set Cash' To Enter A Starting Ammount. (Button Will Be Deleted Once Finished)</p>
<button id="scda" onclick="setcash();">Set Cash.</button>
<br />
<div class="cash">Cash: <span id="cash">0</span></div>
<div>Pack Price: <span id="packprice">50</span></div>
<button class="open" onclick="opencards()">Open Cards.</button>
<br />
<img class="card" src="images/blank.png" id="canvas" />
<img class="card" src="images/blank.png" id="canvas1" />
<img class="card" src="images/blank.png" id="canvas2" />
<img class="card" src="images/blank.png" id="canvas3" />
<img class="card" src="images/blank.png" id="canvas4" />


function setcash(){
var wcash = prompt("Please Enter How Much Cash You Want To Start With", "Cash Wanted");
document.getElementById("cash").innerHTML = wcash;


var cards = new Array("images/1.png", "images/2.png", "images/3.png", "images/4.png", "images/5.png","images/6.png", "images/7.png", "images/8.png", "images/9.png");

var pack = document.getElementById("packprice");
var ccash = document.getElementById("cash");

var pc = Number(pack);
var cash = Number(ccash);

function opencards(){
if (cash >= pc){
var randomNum = Math.floor(Math.random() * cards.length);
document.getElementById("canvas").src = cards[randomNum];
document.getElementById("canvas1").src = cards[randomNum];
document.getElementById("canvas2").src = cards[randomNum];
document.getElementById("canvas3").src = cards[randomNum];
document.getElementById("canvas4").src = cards[randomNum];
cash = cash - pc;
} else{


You're only getting the element itself, but not the actual value of those. You are then trying to get a number from an element. Since the actual elements don't change (regardless of what the innerhtml is set to) you're getting the same result every time in the comparison.

var pack = document.getElementById("packprice"); //this gets you the element
var ccash = document.getElementById("cash"); //this gets you the element

Try instead:

var pack = document.getElementById("packprice").innerHTML;
var ccash = document.getElementById("cash").innerHTML;

You can probably also omit

var pc = Number(pack);
var cash = Number(ccash);