Reputation: 35
The individual variables are being defined and I can alert them, it's when I want to divide one by the other that, not only it doesn't give me an answer, it doesn't even alert a box!
I have the element id with this HTML code:
<p class="margin"><b>Got </b>
</p><input type="number" class="margin" id="iGotThis">
<p class="margin"><b> out of </b></p>
<input type="number" class="margin" id="outOfThis">
and get it into a variable with js and this code:
let iGotThis = document.getElementById("iGotThis").value;
let outOfThis = document.getElementById("outOfThis").value;
let perMade = iGotThis / outOfThis;
and I am trying to alert the result with an alert function:
document.getElementById("submit").click();
}
});
function perFunction() {
alert(perMade);
};
// This entire portion has no use for the variables
var input = document.getElementById("outOfThis");
var perMade = 0;
input.addEventListener("keyup", function(event) {
let iGotThis = document.getElementById("iGotThis").value;
let outOfThis = document.getElementById("outOfThis").value;
let perMade = iGotThis / outOfThis;
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("submit").click();
}
});
// This is where the useless section ends
function perFunction() {
alert(perMade);
};
.margin {
margin-left: 80px;
}
<!DOCTYPE html>
<html>
<body>
<br>
<br>
<p class="margin"><b>Got </b></p><input type="number" class="margin" id="iGotThis">
<p class="margin"><b> out of </b></p><input type="number" class="margin" id="outOfThis">
<br>
<br>
<input type="submit" id="submit" class="margin" onclick="perFunction()">
</body>
</html>
Again, the iGotThis
and outOfThis
variables work, but it is when I try to recall perMade
that it just completely breaks.
Upvotes: 0
Views: 125
Reputation: 10509
The problem is that the variable you are working with is not in scope. As it is being declared from within another function, that is the scope it stays in. To resolve this, you can elevate the scope by declaring the perMade
variable at the start of your code.
// This entire portion has no use for the variables
var input = document.getElementById("outOfThis");
var perMade = 0;
input.addEventListener("keyup", function(event) {
let iGotThis = document.getElementById("iGotThis").value;
let outOfThis = document.getElementById("outOfThis").value;
perMade = iGotThis / outOfThis;
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("submit").click();
}
});
// This is where the useless section ends
function perFunction() {
alert(perMade);
};
.margin {
margin-left: 80px;
}
<!DOCTYPE html>
<html>
<body>
<br>
<br>
<p class="margin"><b>Got </b></p><input type="number" class="margin" id="iGotThis">
<p class="margin"><b> out of </b></p><input type="number" class="margin" id="outOfThis">
<br>
<br>
<input type="submit" id="submit" class="margin" onclick="perFunction()">
</body>
</html>
Upvotes: 1