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
  1. #1
    New to the CF scene
    Join Date
    Sep 2012
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts

    dynamically displaying text with innerHTML

    Hi,

    The following code only works, if my submit is outside the bounds of the form element. If the submit is within the bounds of the form, the dynamically generated text appears for a second, then gets overwritten with the original static text. Can anyone explain why this is? This issue baffles me.

    Code:
     
    <!DOCTYPE html>
    <html>
    <head>
    <title>Fizzbuzz!</title>
    <script>
    function myFunction()
    {
    
    	var beginVal = fbForm.begin.value;
    	var endVal   = fbForm.end.value;
    	var msg = "";
    		for (i = beginVal; i <= endVal; i++)
    		{
    			if ((i%3 == 0) && (i%5 == 0))
    			{
    				msg += i + " fizzbuzz!<br>";
    			}
    			else if (i%3 == 0)
    			{
    				msg += i + " fizz!<br>";
    			}
    			else if (i%5 == 0)
    			{
    				msg += i + " buzz!<br>";
    			}
    			else
    			{
    				msg += i + "<br>";
    			}
    		}
    		
    		document.getElementById("demo").innerHTML= msg;
    }
    </script>
    </head>
    <body>
    <form name="fbForm" >
    Please enter a starting number
    <input type="text" name="begin" value="1">
    <br>
    Please enter an end number
    <input type="text" name="end" value="100">
    </form>
    
    <input type="submit" value="submit" onclick="myFunction()">
    
    <p id="demo">A Paragraph.</p>
    
    </body>
    Thank you in advance for your help!

  • #2
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Posts
    2,762
    Thanks
    55
    Thanked 517 Times in 514 Posts
    a submit button is made to submit a form, which it will try to do, then reload the page. If it is outside the form it doesn't know what it is trying to submit, so will do nothing. Try:
    Code:
    <input type="button" value="submit" onclick="myFunction()">
    which you can put anywhere

    you should also note that values from text inputs are treated as strings even if they look like numbers. Your code would work better like this:
    Code:
    var beginVal = Number(fbForm.begin.value);
    var endVal   = Number(fbForm.end.value);

  • Users who have thanked xelawho for this post:

    icicle (09-15-2012)

  • #3
    New to the CF scene
    Join Date
    Sep 2012
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Thank you so much Xelawho!


  •  

    Posting Permissions

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