So here's what I'm trying to do: in my webpage, I have a lot of HTML forms. If any individual form is submitted, I want the entire form to be replaced with something. However, I haven't been able to do this.
Below is my JavaScript code:
$("#commentreply").each(function() {
var replace = false;
$(this).submit(function() {
// http://stackoverflow.com/q/16323360/1222411
event.preventDefault();
var url = $(this).attr('action');
var nameValue = $(this).find('input[name="name"]').val();
var commentValue = $('#commentEntry').val();
var projectValue = $(this).find('input[name="project"]').val();
var idValue = $(this).find('input[name="id"]').val();
var posting = $.post(url, {
project : projectValue,
id : idValue,
name : nameValue,
comment : commentValue
});
posting.done(function(data) {
$(this).replaceWith("(HTML content to replace form)");
}).error(function(){
alert("An error occurred. Be sure you entered a name and comment and try again");
});
});
});
The idea is that the following HTML code:
<form id="commentreply" name="reply" action="/lib/comments/addComment.php" method="post">
<input type="hidden" name="project" value="project">
<input type="hidden" name="id" value="-1">
Name:<input type="text" id="nameEntry" name="name" size="100"><br>
Comment:<br><textarea id="commentEntry" name="comment" size="255">
Enter comment here</textarea><br>
<input type="submit" value="Submit">
</form>
Will become this when the submit button is hit:
(HTML content to replace form)
Any advice? Would it be better to attach JavaScript to each form rather than use .each() to deal with addressing each form?