137

I have a web page with 3 forms on it. Not nested, just one after the other (they are almost identical, just one hidden variable that's different). A user will only fill in one form, and I'd like to validate/etc all the forms with only one JS script.

So how, when a user clicks the submit button of form#1, do I make my js script only deal with the fields in form1? I gather it has something to do with $(this).parents , but I am not sure what to do with it.

My validation script (which I used elsewhere, with only a single form) looks something like so:


$(document).ready(function(){
    $("#submit").click(function(){
        $(".error").hide();
        var hasError = false;

        var nameVal = $("#name").val();
        if(nameVal == '') {
            $("#name").after('Please enter your name.');
            hasError = true;
        }


        if(hasError == false) {blah blah do all the processing stuff}

So do I need to replace things like $("#name").val() with $(this).parents('form').name.val() ? Or is there a better way to go about this?

Thanks!

isherwood
  • 58,414
  • 16
  • 114
  • 157

5 Answers5

204

You can select the form like this:

$("#submit").click(function(){
    var form = $(this).parents('form:first');
    ...
});

However, it is generally better to attach the event to the submit event of the form itself, as it will trigger even when submitting by pressing the enter key from one of the fields:

$('form#myform1').submit(function(e){
     e.preventDefault(); //Prevent the normal submission action
     var form = this;
     // ... Handle form submission
});

To select fields inside the form, use the form context. For example:

$("input[name='somename']",form).val();
Eran Galperin
  • 86,251
  • 24
  • 115
  • 132
  • You could also use to select all the input children: $(this).children().filter("input") – Pim Jager Nov 22 '08 at 18:17
  • or $("input,textarea,select",form) – Eran Galperin Nov 22 '08 at 18:41
  • 1
    Why can't you use `var form = $(this).form` like in normal Javascript: `function onClick(button) { var form = button.form; }` ??? – Chloe Dec 22 '13 at 01:11
  • `closest('form')` is better as it stops after finding the first matching parent element. `parents('form:first')` traverses the entire DOM and then applies the filter https://api.jquery.com/closest/#entry-longdesc – Ron Dec 13 '21 at 00:40
72

I found this answer when searching for how to find the form of an input element. I wanted to add a note because there is now a better way than using:

var form = $(this).parents('form:first');

I'm not sure when it was added to jQuery but the closest() method does exactly what's needed more cleanly than using parents(). With closest the code can be changed to this:

var form = $(this).closest('form');

It traverses up and finds the first element which matches what you are looking for and stops there, so there's no need to specify :first.

TC0072
  • 843
  • 6
  • 5
54

To get the form that the submit is inside why not just

this.form

Easiest & quickest path to the result.

Moxy
  • 4,162
  • 2
  • 30
  • 49
redsquare
  • 78,161
  • 20
  • 151
  • 159
  • 3
    why the need for the jquery wrapper! – redsquare Jul 18 '13 at 14:54
  • 3
    Because this was asked as a jQuery question too. And as the accepted answer also returns a jQuery object I though that it would be nice. All "why do that with jQuery when you can do it without it the same way" aside. – flu Jul 18 '13 at 15:16
4

i used the following method & it worked fine for me

$('#mybutton').click(function(){
        clearForm($('#mybutton').closest("form"));
    });

$('#mybutton').closest("form") did the trick for me.

charles
  • 307
  • 5
  • 5
3

Eileen: No, it is not var nameVal = form.inputname.val();. It should be either...

in jQuery:

// you can use IDs (easier)

var nameVal =  $(form).find('#id').val();

// or use the [name=Fieldname] to search for the field

var nameVal =  $(form).find('[name=Fieldname]').val();

Or in JavaScript:

var nameVal = this.form.FieldName.value;

Or a combination:

var nameVal = $(this.form.FieldName).val();

With jQuery, you could even loop through all of the inputs in the form:

$(form).find('input, select, textarea').each(function(){

  var name = this.name;
  // OR
  var name = $(this).attr('name');

  var value = this.value;
  // OR
  var value = $(this).val();
  ....
  });
isherwood
  • 58,414
  • 16
  • 114
  • 157
Lathan
  • 853
  • 4
  • 14