Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
Like Tree2Likes
  • 1 Post By DaveyErwin
  • 1 Post By Philip M

Thread: While loop to

  1. #1
    New Coder
    Join Date
    Jun 2014
    Posts
    19
    Thanks
    2
    Thanked 0 Times in 0 Posts

    While loop to

    On the while loop I need it to count up to the number entered. For example, if I enter 5 it will display:

    1
    2
    3
    4
    5

    Code:
    var name = prompt("Input a number", "");
    
    var i = name;
    while(i<=10)
    {
    document.writeln(i + "<br/>");
    i++;
    }

  • #2
    Regular Coder
    Join Date
    Aug 2010
    Posts
    967
    Thanks
    19
    Thanked 211 Times in 209 Posts
    <!DOCTYPE html>
    <html>
    <body>
    <script>
    var name = prompt("Input a number", "");
    var i = 1;
    while(i<=name){
    document.writeln(i + "<br/>");
    i++;
    }
    </script>
    </body>
    </html>
    Krunch likes this.

  • #3
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,919
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    Be aware that prompts and document.write() are considered obsolete and should be used only for testing purposes. You should really use DOM methods to display a message to your users.

    It is a bad idea to use the word name as the name of a variable (you should avoid giving names or id's to your variables/functions/arguments/forms words which are HTML/JavaScript methods/properties/attributes such as name), and particularly so when the variable is supposed to contain a number.

    You can trap NaN errors with || 0

    Code:
    <!DOCTYPE html>
     <html>
     <body> 
    
    <script type = "text/javascript">
     var myNumber = Number(prompt("Input a number", "")) || 0;  // 0 if NaN entered
     var i = 1;
     while (i <= myNumber) {
     document.writeln(i + "<br/>");
     i++;
     }
     </script>
     </body>
     </html>
    Don't forget that values entered by the user are strings unless/until converted to numbers by one of several different methods. That does not matter too much here, but is often the source of unexpected results.
    Last edited by Philip M; 06-25-2014 at 09:41 AM.
    Krunch likes this.

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.


  •  

    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
    •