skip to Main Content

I have a button that is inside of a HTML form, but I want button to submit another form on the page. Both forms have unique IDs. How do I identify which form the button should submit?

2

Answers


  1. Chosen as BEST ANSWER

    Reading <button> documentation was helpful:

    The <form> element to associate the button with (its form owner). The value of this attribute must be the id of a <form> in the same document. (If this attribute is not set, the <button> is associated with its ancestor <form> element, if any.)

    This attribute lets you associate <button> elements to <form>s anywhere in the document, not just inside a <form>. It can also override an ancestor <form> element.

    TLDR use form attribute to reference the target form by its ID, e.g.

    <form id="foo">
    </form>
    
    <form id="bar">
      <button type="submit">Submit Bar</button>
      <button type="submit" form="foo">Submit Foo</button>
    </form>
    

    In this example, clicking "Submit Foo" will submit #foo form.


    1. HTML Setup: Two forms with unique IDs, and a button in the first form.
        <!-- First form with the button -->
        <form id="form1">
            <!-- Form contents -->
            <button type="button" id="submitOtherForm">Submit Other Form</button>
        </form>
        
        <!-- Second form which you want to submit -->
        <form id="form2">
            <!-- Form contents -->
        </form>
    1. JavaScript: Add an event listener to the button to submit the second form.
    <script>
        document.getElementById('submitOtherForm').addEventListener('click', function() {
            document.getElementById('form2').submit();
        });
    </script>

    In this example, the button with the ID submitOtherForm is inside form1. When clicked, it triggers JavaScript to submit form2. Note that the type of the button is set to button to prevent it from submitting form1 (the default behavior if the type were submit).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search