I want to make a general jQuery code which will catch all the submit
events of <form>
subelements including the container element (in case it's a form).
The cases are:
<form>
<button>hi</button>
</form>
<div>
<form>
<button>submit</button>
</form>
</div>
What's the cleanest code to do this?
My current solution is the following:
function submit(e) {
// do something
}
$(containerSelectorOrjQueryObject).on("submit", "form", submit);
$(containerSelectorOrjQueryObject).on("submit", submit);
However, I'd be happy to know if there is a better solution, using just one on
call.
You can use a class attribute for this as a way to set up a delegate to catch the submit event of any child form no matter what the parent element is. Because it is a delegate, this will also catch anything fired by elements that have been dynamically added as well.
Example that includes a single form scenario, multiple forms in div scenario, and a button to add a form dynamically:
var alreadyAdded;
function submit(e) {
// do something
alert(e.target.name);
return false;
}
$("body").on("submit", ".outerContainer", submit);
$("#addAnotherDynamically").on("click", function(e) {
if (typeof(alreadyAdded) === "undefined") {
alreadyAdded = true;
$("#test2").append("<form name='form4'><button>submit 4</button></form>");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body>
<form id="test1" name="form1" class="outerContainer">
<button>submit 1</button>
</form>
<div id="test2" class="outerContainer">
<form name="form2">
<button>submit 2</button>
</form>
<form name="form3">
<button>submit 3</button>
</form>
</div>
<br>
<button id="addAnotherDynamically">Add another form</button>
</body>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With