/    Sign up×
Community /Pin to ProfileBookmark

[RESOLVED] Some for loop help please.

Hi folks. Here’s the code I have so far:

[code]<script language=javascript type=text/javascript>
var i, sum=0;

for (i=1;i<=5;i++)
{
sum = sum+i;
document.write(“The total is: ” +sum);
document.write(“<br>”);
}
</script>[/code]

What I now need to do is modify the above to allow the user to input a value. So basically that would be 1+2+3+4+5+n?

I made an attempt at it, but I just don’t know where to put n in the loop. I am very new to javascript.

Attempt:

[code]
<html>
<head>
<title>For Loop</title>
<script language=javascript type=text/javascript>
var i, sum=0;
var n =eval(document.myform.number.value);

for (i=1;i<=5;i++)
{
sum = sum+i;
document.write(“The total is: ” +sum);
document.write(“<br>”);
}
</script>

</head>
<body>
<form name=”myform” onSubmit=”calculate();”>
<h2>Enter a number</h2>
<p><label for=”number”>Input number here: </label><input type=”text” size=”10″ name=”number” id=”number”/> </p>
<input type=”submit” value=”Calculate”/>
</form>

</body>
</html>[/code]

Anyway thanks. ?

to post a comment
JavaScript

8 Comments(s)

Copy linkTweet thisAlerts:
@blue-eye-labsOct 28.2009 — First things first, I would definitely NOT use that eval() statement to get the number out since there is unvalidated user input and they could put anything (e.g. "alert("hello");" or something annoying).

What you should probably do is create a function which does your calculation for you and then writes it to a specific element. So, exemplia gratia:

[CODE]
//Define the function
function doMySum() {
//First get the number from the user input
//I assume this should be an integer, rather than a float?
var n = document.getElementById("number").value.parseInt();

//Create an empty string to hold your "The total is: ..." stuff
var sum_string = "";

//Create iterator and sum variables
var i;
var sum = 0;

//Now run the for loop
for(i=0; i < n; i++) {
//Add the sum
sum = sum + (i+1);

//Add a <br/> before this line if it's not the first line
if(i>0) { sum_string += "<br/>"; }

//Write the sum string
sum_string += "The total is: " + sum;
}

//Now write the output to a div called "output".
//This will over-write anything currently in there.
document.getElementById("output").innerHTML = sum_string;

//Return false to stop any links being followed or forms being submitted.
return false;
}
[/CODE]


Then you can just add [code=html]onsubmit="return doMySum();"[/code] to the form tag.

Don't forget to create the "output" element (a <div>) should do the trick.

I hope that helps.
Copy linkTweet thisAlerts:
@blue-eye-labsOct 28.2009 — Sorry, that should be
[CODE]
var n = parseInt(document.getElementById("number").value);
[/CODE]

Instead of
[CODE]
var n =document.getElementById("number").value. parseInt();
[/CODE]


Apologies.
Copy linkTweet thisAlerts:
@KorOct 28.2009 — Sorry, that should be
[CODE]
var n = parseInt(document.getElementById("number").value);
[/CODE]
[/QUOTE]

Better
<i>
</i>var n = parseInt(document.getElementById("number").value, [B][COLOR="Blue"]10[/COLOR][/B]);

If no base radix specified, parseInt() might consider some decimal numbers as octal, because, in fact, [B]parseInt([/B][I][COLOR="Blue"]number[/COLOR],[COLOR="Green"]base[/COLOR][/I][B])[/B] method was designed to parse a [COLOR="Blue"]number[/COLOR] from a [COLOR="Green"]certain base[/COLOR] to decimal. It is safer to specify [I]which[/I] is that certain base, 10 in your case.

See:
<i>
</i>var x='0112';
alert(parseInt(x)); //returns 74
alert(parseInt(x,10)); //returns 112
Copy linkTweet thisAlerts:
@blue-eye-labsOct 28.2009 — @Kor:

Thanks for that, I hadn't realised.
Copy linkTweet thisAlerts:
@KrooKedUKauthorOct 28.2009 — Thank-you both for your replies that works perfectly ?

I assume that if I want to limit the number input by the user I would use an if statement and have a message show telling them to input a number between 0 and 20?
Copy linkTweet thisAlerts:
@blue-eye-labsOct 28.2009 — 
I assume that if I want to limit the number input by the user I would use an if statement and have a message show telling them to input a number between 0 and 20?
[/QUOTE]


Yup, just check the value of [B]n[/B] and if it's outside of your range then have some sort of popup, alert, red-div or whatever else you can think of ?
Copy linkTweet thisAlerts:
@KrooKedUKauthorOct 29.2009 — Ok, thanks for the help dude ?
Copy linkTweet thisAlerts:
@blue-eye-labsOct 29.2009 — You're welcome. Mark the thread as resolved.
×

Success!

Help @KrooKedUK spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.30,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...