Reputation: 917
I need to submit a form by clicking a button outside the form. Here is the simple page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>title</title>
<script type="text/javascript">
$(function () {
$("#buy-button").on("click", function () {
$("#refresh-form").submit(function () {
alert('test');
});
});
});
</script>
</head>
<body>
<header>
header
</header>
<div id="main-div">
</div>
</div>
<div id="navigation-div">
<form id="refresh-form" action="test.php">
<button id="map-button">Refresh</button>
</form>
<button id="buy-button">Buy</button>
</div>
<footer>
footer
</footer>
</body>
</html>
When I click the buy-button
it won't refresh the page. What am I missing?
Suppose that I have a list of buttons inside a form, which of them has button
as type, if I can successfully submit the form will I get all the values set for each button anyway or will I get only the values of the button which type has been set as submit
?
Upvotes: 0
Views: 7039
Reputation: 6335
You can achieve what you want without using JavaScript. If you set the form
attribute in the button tag, it will work as a submit button even if it is placed outside the form:
<form id="refresh-form" action="test.php">
<button id="map-button">Refresh</button>
</form>
<button id="buy-button" form="refresh-form">Buy</button>
Upvotes: 0
Reputation: 63
Here is working example we gonna use ajax
<form id="sortContentImagesForm" method="PATCH" action="/">
<div id="sortContentImages">
</div>
</form>
<button id="submit-sorted-images" class="btn btn-success btn-sm"><i class="fa fa-check"></i>Submit Sorted
Images</button>
<script>
$(document).on('click', '#submit-sorted-images', function (e) {
$("#sortContentImagesForm").submit(); // Submit the form
});
$(document).on('submit', "#sortContentImagesForm", function (e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.attr('action');
var type = form.attr('method');
$.ajax({
type: type,
url: url,
data: form.serialize(), // serializes the form's elements.
success: function (payload) {
toastr.success("Updated Successfully");
},
error: function (request, status, error) {
toastr.error(request.responseText);
}
});
});
</script>
Upvotes: 0
Reputation: 741
I would certainly use trigger
like this:
$(function () {
$("#buy-button").on("click", function () {
$("#refresh-form").trigger('submit');
});
});
From jQuery docs on submit():
Forms can be submitted either by clicking an explicit
<input type="submit">
,<input type="image">
, or<button type="submit">
, or by pressing Enter when certain form elements have focus.
It seems to me that manually triggering form submission is a better, workable approach.
Upvotes: 1