Is there a better jQuery solution to this.form.submit();?

前端 未结 8 448
醉梦人生
醉梦人生 2020-12-02 20:13

I want to trigger the submit event of the form the current element is in. A method I know works sometimes is:

this.form.submit();

I\'m wond

相关标签:
8条回答
  • 2020-12-02 20:40

    Similar to Matthew's answer, I just found that you can do the following:

    $(this).closest('form').submit();
    

    Wrong: The problem with using the parent functionality is that the field needs to be immediately within the form to work (not inside tds, labels, etc).

    I stand corrected: parents (with an s) also works. Thxs Paolo for pointing that out.

    0 讨论(0)
  • 2020-12-02 20:43

    Your question in somewhat confusing in that that you don't explain what you mean by "current element".

    If you have multiple forms on a page with all kinds of input elements and a button of type "submit", then hitting "enter" upon filling any of it's fields will trigger submission of that form. You don't need any Javascript there.

    But if you have multiple "submit" buttons on a form and no other inputs (e.g. "edit row" and/or "delete row" buttons in table), then the line you posted could be the way to do it.

    Another way (no Javascript needed) could be to give different values to all your buttons (that are of type "submit"). Like this:

    <form action="...">
        <input type="hidden" name="rowId" value="...">
        <button type="submit" name="myaction" value="edit">Edit</button>
        <button type="submit" name="myaction" value="delete">Delete</button>
    </form>
    

    When you click a button only the form containing the button will be submitted, and only the value of the button you hit will be sent (along other input values).

    Then on the server you just read the value of the variable "myaction" and decide what to do.

    0 讨论(0)
提交回复
热议问题