How do I select the parent form based on which submit button is clicked?

前端 未结 5 832
孤城傲影
孤城傲影 2020-12-02 07:57

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 i

相关标签:
5条回答
  • 2020-12-02 08:11

    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.

    0 讨论(0)
  • 2020-12-02 08:19

    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();
      ....
      });
    
    0 讨论(0)
  • 2020-12-02 08:28

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

    this.form
    

    Easiest & quickest path to the result.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-02 08:35

    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();
    
    0 讨论(0)
提交回复
热议问题