0

I have a page that has 6 forms that all have a value with the same name 'audit_id_upload'. Currently I have one of them being validated (I'm just looking for empty values) with...

function validateForm()
{
var x=document.forms["audit_upload"]["audit_id_upload"].value;
if (x==null || x=="")
  {
  alert("Please Select an Audit");
  return false;
  }
}
</script>

Can I adapt this to validate the other forms as well without having to repeat it 5 more times?

Thanks

2 Answers 2

3

Since you have a input element with audit_id_upload in every form, you could pass the name of your form to this function and use it to validate the item.

function validateForm(fName)
{
   var x=document.forms[fName]["audit_id_upload"].value;
   if (x==null || x=="")
   {
      alert("Please Select an Audit");
      return false;
   }
   return true;
}

and call it on the for onSubmit event.

<form name='f1' onsubmit="return validateForm('f1')">

</form>

<form name='f2' onsubmit="return validateForm('f2')">

</form>

<form name='f3' onsubmit="return validateForm('f3')">

</form>
Sign up to request clarification or add additional context in comments.

4 Comments

Gah! Beat me to it. I was about to offer the same solution. A good solution nonetheless :)
Brill, I was using the onsubmit but I was thinking that I somehow had to have a reference for every form name in the script, didn't think to pass the value like that, thanks!
Nice guys. I hope it help you, and remember to check the anwser as a anwser to help other users with the same problem and improve the SO website. :)
nice solution, but maybe you can just pass "this" to the function, so the function doesn't need to redo the search to the form. :)
0

Try this:

<html>
    <script type="text/javascript">
    function test(theform)
    {
        if (theform.thefield.value == "foo") return true;
        else return false;
    }
    </script>
    <body>
        <form action="" onsubmit="return test(this);">
        <input type="text" value="" name="thefield" />
        <input type="submit" />
        </form>
        <form action="" onsubmit="return test(this);">
        <input type="text" value="" name="thefield" />
        <input type="submit" />
        </form>
        <form action="" onsubmit="return test(this);">
        <input type="text" value="" name="thefield" />
        <input type="submit" />
        </form>
    </body>
</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.