Jump to content

Multiple functions in one script


sseeley

Recommended Posts

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

Link to comment
https://forums.phpfreaks.com/topic/207982-multiple-functions-in-one-script/
Share on other sites

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.

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()

...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>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.