Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submit an HTML form without having a submit button?

Tags:

html

jquery

forms

Can I submit a html <form> with <div> instead of <input type="submit"> ?

Like this:

<form method="post" action="" id="myForm">
  <textarea name="reply">text</textarea>
</form>

<div>Submit the form by clicking this</div>
like image 538
Frantisek Avatar asked Oct 09 '11 16:10

Frantisek


People also ask

How can we submit a form without submit button in HTML?

The form can be submitted without using submit button by implementing a specific event attribute or by clicking the link. This task can be done by using the OnClick event attribute or by using the form. submit() method in Javascript.

How do you create a form that does not submit a button?

Set it to type="button" to produce a button that doesn't submit the form. In the words of the HTML Standard: "Does nothing."

How can I submit a form without JavaScript?

Use the <noscript></noscript> tags to define a "normal" submit-button when javascript is disabled. Show activity on this post. You could maybe use the <noscript> tag and encapsulate the above code with the button type as submit. If the client has js, the code inside the noscript will be ignored.

Can we submit form without form tag?

It is actually possible to "submit" a "form" without form-tags. what you need is an ajax-function, e.g. with jquery, which will get the values by id. But there is no reason not to use a form tho. you should use form tag.


1 Answers

The method you can use to submit a specific form is the following:

// Grab the form element and manually trigger the 'submit' method on it:
document.getElementById("myForm").submit();

So in your example, you can add a click event handler on any element you like and trigger the form's submit method through that:

<form method="post" id="myForm">
  <textarea name="reply">text</textarea>
</form>

<div class="submit">Submit the form by clicking this</div>
const myForm = document.getElementById("myForm");
document.querySelector(".submit").addEventListener("click", function(){

  myForm.submit();

});

And if you want to do it jQuery style (which I do not recommend for such a simple task);

$("#myForm").submit();

In its full form:

const myForm = $("#myForm");
$(".submit").click(function(){

  myForm.submit();

});

References:

  • The submit() method of HTML Form elements (native JavaScript API)
  • The jQuery submit() API
like image 162
japrescott Avatar answered Sep 30 '22 02:09

japrescott