2015-11-01 67 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

您可以为每个使用的输入字段添加一个类,并按该类进行过滤。所以你会避免使用所有的输入域值。