Jump to content

JavaScript for loop problem

Recommended Posts

Hi Guys,
I am teaching myself JavaScript. This little program works but I am unable to pass the result to onclick. Could you please help. Thanks.
<!doctype html>
<h2> 12 Times Table </h2>
function 12Times()
var times=1
for (times =1;times<=12; times++)
alert(times + " times 13 is " +(times * 13) + "<br>");
<input type="button" onclick="12Times()" value="12Times">

Share this post

Link to post
Share on other sites



It looks like you're missing the opening and closing braces { } for the for loop.


Also to note, the times variable, you can set it inside the for loop instead, like this: for(var times = 1; times <= 12; times++)

Share this post

Link to post
Share on other sites

Sorry, I thought it might be better without a for-loop for this. The tutorial for-loop is here...




You shouldn't begin any identifiers with a number, so id's or function names or variable names should start with a letter. Use something like f12 rather than 12f.

<!DOCTYPE html><html><head><title>13</title><script>window.onload = init;var times;function init() {times = 1; out = document.getElementById('out');document.getElementById('btn').onclick = times13; }function times13(){ if (times <= 13){out.innerHTML += times + " times 13 is " + (times * 13) + "<br/>";times++;}else{times = 1;out.innerHTML = '';}} </script></head><body><h2> 13 Times Table </h2><input type="button" id="btn" value="13Times"/><br/><br/><div id="out"></div> </body></html>
Edited by davej

Share this post

Link to post
Share on other sites

Thanks DaveJ.


Your respond was very helpful.

Share this post

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Create New...