html – How can I submit using a button that is not inside the form?

Question:

I have a form very similar to the one I put below. This is just a demo but it illustrates the doubt I have.

<!DOCTYPE>
<html>
<head>
    <title>Formulario</title>
</head>

<body>
    <form id="CreateForm" action="/create" method="post">
        <div>
            <label for="campo1">Campo1</label>
            <input type="text" id="campo1" name="campo1">
        </div>
        <div>
            <label for="campo2">Campo2</label>
            <input type="text" id="campo2" name="campo2">
       </div>
    </form>

    <button type="submit">
        Enviar
    </button>
 </body>

</html>

How can I do so that when I click on the button the form is submitted without using javascript?

Answer:

In HTML5 a new mechanism was introduced to separate the form elements (buttons, inputs, etc) from the form. The form attribute associates a control with a <form> :

<form id="CreateForm" action="/create" method="post">
    <input type="text" name="foo" />
</form>

<button type="submit" form="CreateForm">Enviar</button>

It is only necessary to assign the same id of the form in the form attribute of the element.

Scroll to Top