On my mainPage.html, I dynamically created multiple forms each with different values in their input tag.. this is my mainPage.html:
<form class='voteForm' method="post" action="/post/likePost/">
<button class="voteButton" type="submit">
</button>
<input type="hidden" name="postID" value="1" />
</form>
<form class='voteForm' method="post" action="/post/likePost/">
<button class="voteButton" type="submit">
</button>
<input type="hidden" name="postID" value="2" />
</form>
<form class='voteForm' method="post" action="/post/likePost/">
<button class="voteButton" type="submit">
</button>
<input type="hidden" name="postID" value="3" />
</form>
As you can see, all three forms are similar, just their value is different. Now, this is my JS function
<script type='text/javascript'>
$('.voteForm').click( function() {
event.preventDefault();
alert($('.voteForm').serialize());
});
</script>
The problem is, whenever I click on any of the forms, it keeps automatically assuming that the form clicked is the last form which has a value of '3' in input, so it keeps altering the number 3 regardless of which form I click. I'm assuming this is because I did
$('.voteForm').click
and all three forms have the same class so it automatically takes the last form and runs the function. How do I make it so that it takes the form who's button I clicked and alerts the input-value of the clicked form WITHOUT changing the class or adding an ID to the form? Is there a way? I need all the forms to be the same (except for their input-value's).
Your click event handler is given a reference to the button that was clicked as the this
context for the callback function. Use that to select the correct form:
$('.voteForm').click( function() {
event.preventDefault();
alert($(this).closest('form').serialize());
});
Better yet, rearchitect your markup so you have a single form, or no form at all, and just use the value of the thing which is being clicked. Using three forms for this which all submit to the same URL is a little odd.