2015-12-19 92 views
0

我在做這項工作時遇到了麻煩。 我需要在同一頁面上有多個表單...我嘗試過無數次的事情,但似乎沒有任何工作。同一頁上的多個表單AJAX

我在這裏要做的是識別每個表單(以某種方式),以便在頁面上提交該表單而不是FIRST表單。下面的代碼工作,但始終提交相同的形式,第一個!

這裏是我當前的代碼

JS:

$(document).ready(function(){ 

    $('.submit').on("click", function() { 

     var artworkId = $("#inquirebox").data("artworkid"); 

     $.post("send.php";, $("#artinquire"+artworkId).serialize(), function(response) { 
      $('#success').html(response); 
     }); 

     return false; 

    }); 

}); 

HTML:

<div id="inquirebox" data-artworkid="<?php echo 456;?>"> 
    <form action="" method="post" id="artinquire<?php echo 456;?>" data-artworkid="<?php echo 456;?>"> 
     <label for="name">Name:</label><br /> 
     <input type="text" name="name" id="name" /><br /> 

     <label for="email">Email:</label><br /> 
     <input type="text" name="email" id="email" /><br /> 

     <label for="message">Message:</label><br /> 
     <textarea name="message" id="message"></textarea><br /> 

     <input type="hidden" name="id" value="<?php echo 456;?>"> 
     <input type="hidden" name="artist" value="<?php echo $title1; ?>"> 
     <input type="hidden" name="url" value="<?php echo $uri1; ?>"> 
     <input type="hidden" name="artwork" value="<?php echo $artwork1; ?>"> 

     <input type="button" value="send" class="submit" id="submit" data-artworkid="<?php echo 456;?>"> 
     <div id="success"></div> 
    </form> 
</div> 
+0

因此,所有DIV的封裝形式都有相同的ID,那麼所有的都是'inquirebox',並且你正試圖用一個數據屬性來識別它們,這是出於某種奇怪的原因?當你做'$(「#inquirebox」)。data(「artworkid」)時,你總是得到第一個,因爲ID是唯一的,並且jQuery不希望有比第一個更多的東西? – adeneo

+0

是真的。我怎樣才能讓每個表單封裝具有不同的ID,並能夠用jQuery來識別它,以便知道我想提交的一個呢? –

回答

1

您使用周圍的形式全部DIV包裝相同的ID。

ID必須是唯一的,所以你可以使用類來代替,但你根本不需要任何標識符,也不需要數據屬性,.submit按鈕位於表單內,所以你需要的是this.form ,以上jQuery'ish $(this).closest('form')獲取父形式

$(document).ready(function(){ 

    $('.submit').on("click", function() { 

     var form = $(this).closest('form'); 

     $.post("send.php", form.serialize(), function(response) { 
      form.find('.success').html(response); 
     }); 

     return false; 

    }); 
}); 

然而,你應該使用類#success元素基於表單找到它。

+0

哇!非常感謝你@adeneo。整個事情我太過複雜了。 –

相關問題