www.webdeveloper.com
Results 1 to 3 of 3

Thread: Redefine variable value within while loop

  1. #1
    Join Date
    Jan 2012
    Posts
    6

    Redefine variable value within while loop

    Hi all,

    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.

    Can anyone see how I can fix it?

    Thank you

  2. #2
    Join Date
    Oct 2010
    Location
    Versailles, France
    Posts
    1,266
    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 ...
    Last edited by 007Julien; 01-20-2012 at 04:30 AM.

  3. #3
    Join Date
    Jan 2012
    Posts
    6
    Thank you 007Julien,

    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);
    }


    Thanks again

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles