I have a several forms that are output from a database on the same page. It works fine when I don\'t use ajax. When I use Jquery it will only work for the first form. Could
All the forms and the fields have the same name / class. So when you do
var hardSoft = $('.hardSoft').val();
you only get the value of the first element with class hardSoft
.
You can get the "parent" form element with .closest() and use .serialize() to create the data string:
$('.updateSubmit').live('click', function() {
var $form = $(this).closest('form'); // get the form element this button belongs to
var theData = $form.serialize(); // generates the data string
$.ajax ({
type: 'POST',
url: '/updateGrab.php',
data: theData,
success: function(aaa) {
// append return data to the current form
$form.append('<div class="forSuccess">'+aaa+'</div>');
} // end success
}); // end ajax
return false;
)};
Just a note: You can save a lot of time coding if you serialize those forms.
$('.updateSubmit').live('click', function() {
$.post("updateGrab.php", $("#yourform").serialize());
}
Source:
http://api.jquery.com/serialize/
The problem is that selectors like $('.hardSoft')
will select several elements (since there are multiple forms) and then .val()
will take the value of the first. You could try finding the form using .parents('form')
and then taking its children .children('.hardSoft')
.
$('.updateSubmit').live('click', function() {
var currentForm = $(this).parent();
var hardSoft = currentForm.children('.hardSoft').val();
// ... etc.
On the other hand, this is a rather common task. Take a look at the jQuery Form plugin, which allows you to do the same using much less code. It's probably also more reliable and has several features that you might want to use later in your project.
I guess adding the context within your jQuery selectors could help. Give a try to :
var hardSoft = $('.hardSoft', $(this).parent()).val();
on every selector