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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

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