Get defaultvalue

I got a problem with my javascript code. I want to compare the value before the random number generator and the value after.

function hoger(){
	var y = document.getElementById("getal"); //Value before
	var x = document.getElementById("getal"); //Random number generator
	x.innerHTML = Math.floor((Math.random() * 100) + 1); // x=value after
	
	if(x < y){ //compare with operator
		min1();
	} else {
		plus1();
		alert(y);
	}
}

At this moment the if else statement won’t work. It goes directly to the else part.

Hi BarkiBerkan,

It seems that your problem is that ‘y’ is actually a dom node and not a number and what you want to do is retrieve the contents of y and parse them as an integer in the following way:

function hoger(){
	var y = parseInt(document.getElementById("getal").innerHTML, 10); //Value before
	var x = document.getElementById("getal"); //Random number generator
	x.innerHTML = Math.floor((Math.random() * 100) + 1); // x=value after
	
	if(x < y){ //compare with operator
		min1();
	} else {
		plus1();
		alert(y);
	}
}

Hope it helps,

Andres

1 Like

Hi @BarkieBerkan, x and y hold references to the same element, so it will always be so that x === y… and even after you set the .innerHTML, they will still refer to the same element. Also, comparison operators (such as less than) only make sense with numbers or strings; so you’d have to get the .textContent (which is a string) and convert that to a number first (e.g. using parseFloat()):

var el = document.getElementById('getall')
var valueBefore = parseFloat(el.textContent)
var newValue = Math.floor((Math.random() * 100) + 1)

el.textContent = newValue

if (valueBefore < newValue) {
  // ...
} else {
  // ...
}

PS: Or if that #getall element is an input element with an actual value (as opposed to text content), you might compare its .value and .defaultValue.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.