shadowayex Posted June 16, 2008 Share Posted June 16, 2008 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 More sharing options...
jeffman Posted June 16, 2008 Share Posted June 16, 2008 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 More sharing options...
justsomeguy Posted June 18, 2008 Share Posted June 18, 2008 You can use parseInt to convert the string to a number. var numofchoices = parseInt(prompt("How many choices?","1"), 10);if (isNaN(numofchoices)){ alert("You must enter a number"); return;} Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.