PDA

View Full Version : Passing multiple arguments to functions onclick


delinear
03-02-2005, 11:30 AM
Hi all,

I'm writing some javascript to do a very basic form validation (just checking for blank fields). The thing is I want a generic function that can be used for many different forms, but in order to do so I need to pass all fields from the relevant form to the function and validate them onclick.

Is there a way to pass several variables as an array or would I have to pass them as a string with a separator and then turn them into an array in the function itself?

jbot
03-02-2005, 11:52 AM
you don't need to do any of that.

just loop round the form's elements like so:

for (var i=0, aElms=document.forms[0].elements; i<aElms.length; i++)
{
...
}

delinear
03-02-2005, 12:02 PM
Thanks for the swift reply. The problem though is that there are several forms on each page and not all elements in each form are required, so I only need to validate certain fields from a certain form. I could build just a function for each form, I know, but that seems like overkill.

jbot
03-02-2005, 12:09 PM
The problem though is that there are several forms on each page and not all elements in each form are required, so I only need to validate certain fields from a certain form.

try something like this, then:

function validate(oFrm)
{
for (var i=0, aElms=oFrm.elements; i<aElms.length; i++)
{
if (aElms[i].className.indexOf("required")!=-1)
{
...
}
}
}


<form ... onsubmit="return validate(this)">
<input type="text" ... class="required">
<textarea ... class="required"></textarea>
</form>

delinear
03-02-2005, 12:59 PM
That looks like it'll do the job (won't be able to test it until later now) thanks :thumbsup: