2015-11-01 57 views
0

我已經列出了一些產品,並通過添加到購物車按鈕將一些輸入值添加到購物車。如何獲得此div內的輸入?

例如:我列出了10個產品,每個產品都有1到7個輸入字段,每個輸入都有name="barrel"屬性。

我使用這個jQuery代碼來獲取輸入值:

$('input[name^=barrel]').each(function(){ 
     var attribute = $(this).data('attribute'); 
     var count = $(this).val(); 
     barrel.push({ 
      count: count, 
      attribute: attribute 
      }); 
    }); 

的問題是,從所有產品全部投入得到的值。但我只想從我按下添加到購物車的產品中獲取輸入值。

請給我一個建議。謝謝

+0

外div有一個id或獨特的類? – baao

回答

1

如果你有以下的html:

<div class="product"> 
    <input type="text" name="barrel"> 
    <input type="text" name="barrel"> 
    <input type="text" name="barrel"> 
    <input type="text" name="barrel"> 

    <a href="#" class="add-to-cart">Add to Cart</a> 
</div> 

<div class="product"> 
    <input type="text" name="barrel"> 
    <input type="text" name="barrel"> 
    <input type="text" name="barrel"> 
    <input type="text" name="barrel"> 

    <a href="#" class="add-to-cart">Add to Cart</a> 
</div> 

你應該使用這個腳本:

$(function() { 
    barrel = []; 

    $('.add-to-cart').click(function(){ 
     $(this).parents('.product').find('input[name="barrel"]').each(function(){ 
      var attribute = $(this).data('attribute'); 
      var count = $(this).val(); 
      barrel.push({ 
       count: count, 
       attribute: attribute 
      }); 
     }); 

     return false; 
    }); 
}); 
0

您可以爲每個使用的輸入字段添加一個類,並按該類進行過濾。所以你會避免使用所有的輸入域值。