2011-12-22 17 views
2

我有一個小問題,基本上我有一個隱藏的輸入按鈕,它是從數據庫表中加載一個唯一值:<input type="hidden" name="ProductId" class="ProductId" value='.$row["ProductId"].' />此按鈕重複根據有多少行分配唯一的ID到<input>按鈕,並閱讀它使用jquery

while ($row = $result->fetch()) { 
    echo '<table class="cart-row" cellspacing="0" cellpadding="0" width="100%">'; 
    echo '<tbody>'; 
    echo '<tr>'; 
    echo '<td width="75"><img border="0" width="59px" height="78px" title="" alt="" src=' . $row["ImagePath"] .'></td>'; 
    echo '<td width="203"><span class="itemElements itemName">'. $row["Name"] .'</span></td>'; 
    echo '<td width="203"><input type="submit" class="btnMinus linkbtnType2" value="-"><input type="submit" class="btnPlus linkbtnType2" value="+"></td>'; 
    echo '<td width="135"><span class="qtyNum">('. $row["Qty"] .')</span> <br />'; 
    echo '<input type="hidden" name="ProductId" class="ProductId" value='.$row["ProductId"].' />'; 
    echo '<span class="qtyRemoveLink"><input type="submit" class="btnRemove linkbtn" value="Remove"></td>';        
    echo '<td width="180"><span class="itemElements orderStatus">In Stock Usually dispatched within 24 hours</span></td>'; 
    echo '<td width="175" class="itemPriceRow"><span id="itemPrice">€ '. $row["Price"] .'</span></td>'; 
    echo '</tr>'; 
    echo '</tbody>'; 
    echo '</table>'; 
    echo '<br>';        
} 

im使用一個jQuery方法使用讀取來自隱藏按鈕但是它僅讀取來自所產生的第一輸入按鍵的值該值:通過該方法返回。我嘗試將ID從一個ID改爲一個類,但沒有運氣。

這是jQuery的方法:

$('.btnRemove').click(function() { 
    var productId = $(".ProductId").val(); 
    $.ajax({ 
     type: "POST", 
     url: "functions/deleteCartItem.php", 
     data: "productId="+productId+ "", 
     success: function(msg){ 
      alert(msg); 
     } 
    }) 
}) 

一個可能的解決方案,我能想到的是一個獨特的id添加到每個按鈕,以便它們可以被識別,不僅名字,但也id。然而,這在從jQuery方法中讀取時會產生問題。

任何想法?

回答

1

嘗試:

var productId = $(this).closest('tr').find(".ProductId").val(); 

this$('.btnRemove')的DOM元素。

jQuery(this).closest("tr")我們旅行了DOM樹搜索第一tr元素。

從這裏我們搜索.ProductId

安德烈亞斯

+0

歡呼隊友它的工作原理...良好的思維BTW) – 2011-12-22 09:57:19

1

你在你的假設是正確的,這是因爲你被類,這是造成問題的參考。你var productId = $(".ProductId").val();將返回所有.ProductId元素的數組,並val()只會返回第一項的值。

要解決這個問題,你需要獲得.ProductId元件,它在作爲.btnRemove元素造成的單擊事件,像這樣同一容器:

$('.btnRemove').click(function() { 
    var productId = $(this).closest("td").find(".ProductId").val(); // amended selector 
    $.ajax({ 
     type: "POST", 
     url: "functions/deleteCartItem.php", 
     data: "productId="+productId+ "", 
     success: function(msg){ 
      alert(msg); 
     } 
    }) 
}) 
0

你應該嘗試:

var productId = $(this).closest('tr').find("input[name=ProductId]").val(); 
1

它不會返回正確的值,請嘗試類似於

var productId = $(this).parent().find(".ProductId").val(); 

var productId = $(this).parent().children(".ProductId").val(); 

var productId = $(this).prev(".ProductId").val(); 

var productId = $(this).siblings(".ProductId").val(); 

小提琴:http://jsfiddle.net/fwM3T/

+0

'closest'只會處理父母,而不是你的第二個版本,「兄弟姐妹」是一個更好的選擇。 – kapa 2011-12-22 09:27:04

+0

更新了代碼..希望所有人都能工作.. – 2011-12-22 09:37:14