Reputation: 105
I'm trying to write a jQuery code that sends serliazes the formData I'm submitting from any html page. But what if a html page have multiple forms in it ? how can I know what form I'm submitting ? I'm trying to have a log of the activities I'll be doing on any html page, so without making changes to html code, how can I get the form data of a particular form on a webpage that contains more than one form.
$( "*",document.body ).submit(function( event ) {
console.log( $( this ).serializeArray() );
event.preventDefault();
});
this is the function I wrote but it'll work on any submitted form without knowing which one it is.
Upvotes: 1
Views: 739
Reputation: 14702
you can acces all atribute form using this keyword , wich represent current submited form
by example identifying your form wether by id , name ... , add to each one an id then use
javascript => this.name
or jQuery => $(this).attr('name')
see below snippet:
$( "*",document.body ).submit(function( event ) {
console.clear();
console.log("form id =",$(this).attr("id"));
console.log("form name =",$(this).attr("name"));
// or console.log("form id =", this.id);
event.preventDefault();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="myFirstForm" id="one">
<input name="one" type="text" value="text1" />
</form>
<form name="mySecondForm" id="two">
<input name="two" type="text" value="text2" />
</form>
<form name="myThirdForm" id="three">
<input name="three" type="text" value="text3" />
</form>
Upvotes: 1
Reputation: 101
You can use id
prop, so you can select each form with $('#id')
, and you can add that prop by JavaScript, without needing to mess with the HTML itself. As stated before by Barmar, using this.name
you give you the name of the current form, so you can iterate all the forms in the page, and accessing the name (and other atributes as well) of each one, this way you can have better control in whatever you need to do with each form.
Upvotes: 1