Jquery and multiple forms on a page

前端 未结 4 2007
[愿得一人]
[愿得一人] 2021-01-17 06:30

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

相关标签:
4条回答
  • 2021-01-17 06:59

    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;
    )};
    
    0 讨论(0)
  • 2021-01-17 07:07

    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/

    0 讨论(0)
  • 2021-01-17 07:18

    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.

    0 讨论(0)
  • 2021-01-17 07:20

    I guess adding the context within your jQuery selectors could help. Give a try to :

     var hardSoft = $('.hardSoft', $(this).parent()).val();
    

    on every selector

    0 讨论(0)
提交回复
热议问题