Reputation: 652
I have a page on my site where I got n+1 forms (n being the number of images on the site)
I have this piece of javascript to submit the forms without the user seing it directly:
$('#commentform').on('submit', function(){
$.post($(this).attr('action'), $(this).serialize(), function(response){
var imgid = $(this).find("input[name='imageid']").val();
$('#comment-'+imgid).modal('hide');
},'json');
return false;
});
That code will submit the form in a modal like this one:
<div id='comment-<?php echo $image->id; ?>' class='modal hide fade' tabindex='-1' role='dialog' aria-labelledby='myModalLabel' aria-hidden='true'>
<div class='modal-header'>
<button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button>
<h3 id='myModalLabel'>Tilføj kommentar til billede <?php echo $orig_name; ?></h3>
</div>
<form action="<?php echo base_url(); ?>order/do_updateComment/<?php echo $image->id; ?>" method="POST" id="commentform">
<div class='modal-body'>
<textarea name="comment" rows="3" class="span6" placeholder="Skriv din kommentar her..."><?php echo $image->comment; ?></textarea>
<input type="hidden" name="imageid" value="<?php echo $image->id; ?>" />
</div>
<div class='modal-footer'>
<button class='btn' data-dismiss='modal' aria-hidden='true'>Luk</button>
<input type="submit" name="submit" class='btn btn-primary' value="Gem kommentar" />
</div>
</form>
</div>
This works perfect for the first form on the page - all the rest gets submitted the wrong way (with a redirect to the submission page)
What am I missing here? I am suspecting it to be because of the use of id="commentform"
on all of the forms, but how else could this be done? I got one form on the site that needs to be submitted the normal way.
Also on a side-note, I want to close the modal once the submit has finished, which should be done with these lines of code:
var imgid = $(this).find("input[name='imageid']").val();
$('#comment-'+imgid).modal('hide');
inside the javascript (complete is in the top of the question)
However, that does not work either.. The modal stays open..
I am running the whole thing on Bootstrap 2.x with jquery 1.9.0
Upvotes: 0
Views: 759
Reputation: 939
The reference to $(this) is dropped when you're in the callback. Save the reference outside of the post and it should work.
Upvotes: 1
Reputation: 57719
I am suspecting it to be because of the use of id="commentform" on all of the forms
Correct, ids must be unique. Using classes is the common way to select multiple similar elements.
Upvotes: 1