Hobby_Web_programmer
Hobby_Web_programmer

Reputation: 775

Referencing a form assigned to a variable in jQUERY

I have a form with id='form1' as well as another one with 'form2'. On submit, i want to pass both forms as objects to a single validate function which can validate them. I am confused on how to do this. If i do something like

var form = $('#form1');
Validate(form);

how do i access the text-fields of the variable form? i don't want to write duplicate validate functions as both forms are ALMOSt similar.

Upvotes: 0

Views: 63

Answers (4)

Ben Wong
Ben Wong

Reputation: 1987

Assuming both forms are similar:

ValidateForm($("#form1, #form2"));

function ValidateForm(forms){

   forms.each(function(){

      $(this).find('input[type=text]').each(function(){

        //Do something to validate text field


      })

      $(this).find('input[type=checkbox]').each(function(){

        //Do something to validate checkbox


      })

    })

 }

Upvotes: 0

Nikhil N
Nikhil N

Reputation: 4577

You can do following also...

A Complete example is here...

function validate(formid){
    var form = $("#"+formid);
    var name = form.find("#name");
    var number = form.find("#number");
    alert(name.val());
    alert(number.val());
}

    validate("form1");
    validate("form2");

Upvotes: 1

ezakto
ezakto

Reputation: 3194

With the name of the fields, you can do this:

function Validate(form) {
  form = form[0]; // raw element
  if (check_syntax(form.name.value)) { doSomething(); }
  if (check_syntax(form.email.value)) { doSomething(); }
  if (check_syntax(form.anotherfield.value)) { doSomething(); }
}

If every field in the form has a name, you can access it via form.fieldName or form['fieldName'].

Regards.

Upvotes: 0

Khanh TO
Khanh TO

Reputation: 48972

Try .find. Your form will serve as the context and you could reuse it for different forms.

See below:

var form = $('#form1');
function Validate(form){
    var field1 = form.find(".field1");
}

Upvotes: 0

Related Questions