Jump to content

Loop Problems


shadowayex
 Share

Recommended Posts

Ok, so I wrote a loop that I thought was going to work properly, and it does, for the first time through it. The script is for an admin tool to add choices to a voting page. The HTML code part looks like this:

<script type="text/javascript">var i = 1;function addChoices() { var numofchoices = prompt("How many choices?","1"); if(i > 1) {  numofchoices = numofchoices + i; } while(i <= numofchoices) {  document.getElementById("newchoices").innerHTML += "<input type=\"text\" name=\"choice" + i + "\" value=\"\" /><br />";  i = i + 1; }}function geti() { alert(i);}</script>

I use the geti() function to see what i is, to make sure if the admin does the loop again, it doesn't make areas that have names that are already taken. The first write of the script works perfectly. When admins write it again, however, it writes a whole lots more fields Than it's supposed to. When the admins check i, it's definitely not the number they put in. it usually ranges from 12-34, depending on the combination of numbers inputed. Any ideas why this is happening?

Link to comment
Share on other sites

First reaction without a complete examination:return values from a prompt are strings, not nums. That's a problem sometimes since JS uses the + operator to add AND concatenate. That's when "1" + "1" = "11", not 2. JS will recast types automatically, if you give it the correct hints. i = "1"; j = 1 + i; j returns 2, because 1 + anything expects a number. So if you have a num value, try putting it earlier in the equation. Or, since you can't multiply a string, you can easily cast all strings to nums just by multiplying by 1. Thus i = "1"; j = (i*1) + 1; j returns 2That's my first guess, anyway.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...