I am new to programming and therefore have what is probably an elementary problem.
I'll show you the code and then explain the problem.
// A function to check the validity of the user's input
function inputInRange(msg,min,max) {
while(isNaN(msg) || msg<min || msg>max) {
alert ('Your amount was invalid');
var msg = parseInt(prompt(message));
}
alert('You purchased '+ msg +' tokens.');
}
// Function that allows the user to purchase tokens
function buyTokens() {
var balObj = document.getElementById("balance");
var msg = parseInt(prompt(message));
inputInRange(msg,MIN_PURCHASE,MAX_PURCHASE);
balObj.value = parseInt(balObj.value) + parseInt(msg);
}
Once this code is executed using an invalid value (in order to enter the while loop) the balObj.value is adding the orignal invalid value of msg and not the new value defined in the while loop.
The msg define in the while loop is a local variable in the inputInRange function. Return the new value or modify the code which seem complicated.
Give the user a message and stop your script with a return to let the user correct the data without appreciations ...
I am aware that my code is probably complicated and messy but this is my first programming subject at uni and I am a complete beginner.
My code is working the way I want it to and now looks like this:
// A function to check the validity of the user's input
function inputInRange(msg,min,max) {
var balObj = document.getElementById("balance");
while(isNaN(msg) || msg<min || msg>max) {
alert ('Your amount was invalid');
return;
}
alert('You purchased '+ msg +' tokens.');
balObj.value = parseInt(balObj.value) + parseInt(msg);
}
// Function that allows the user to purchase tokens
function buyTokens() {
var msg = parseInt(prompt(message));
inputInRange(msg,MIN_PURCHASE,MAX_PURCHASE);
}
Bookmarks