sseeley Posted July 16, 2010 Share Posted July 16, 2010 I am trying to create a while loop to create multiple function scripts to validate some entries on my PHP page, however I cannot seem to get the loop to work correctly. Any help would be much appreciated. <script> var i = 0; var ii = 64; while (i < ii) { var validate = "validate" + i"; function validate + () { var teamName = document.getElementById("teamName").value; alert(teamName); } i++; } </script> Stuart Quote Link to comment Share on other sites More sharing options...
Psycho Posted July 17, 2010 Share Posted July 17, 2010 Why on earth would you want to programatically create functions? If you can do that programatically, then you could just as easily create one function that takes the appropriate parameters. The functions you are apparently trying to create above do EXACTLY the same thing, so there is no purpose at all for that. Otherwise I would provide an example to your specific situation. Quote Link to comment Share on other sites More sharing options...
.josh Posted July 17, 2010 Share Posted July 17, 2010 uh yeah...you seem to be completely missing the point of a function... functions are for when you have some code being used over and over in places and instead of having the code over and over again you wrap it up and slap a label on it and call it. Anyways, supposing for whatever reason you want to continue down this futile path...you can't dynamically create functions like that. Look into prototyping or eval() Quote Link to comment Share on other sites More sharing options...
Psycho Posted July 18, 2010 Share Posted July 18, 2010 ...you can't dynamically create functions like that. Sure you can, he just has the syntax wrong. I suspect you could make the function name dynamic but a simpler solution is to just use an array: <html> <head> <script type="text/javascript"> var validate = new Array(); for (var i=0; i<64; i++) { validate[i] = function() { var teamName = document.getElementById("teamName").value; alert(teamName); } } </script> </head> <body> <input type="text" name="teamname" id="teamname" /><br /> <button onclick="validate[2]();">Invoke function validate[2]</button> </body> </html> Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.