Petre Gabriel
Petre Gabriel

Reputation: 141

How to get only the inputs inside this div?

I have listed some products, and I add the values from some inputs to a shopping cart with an Add to Cart Button.

For example: I have listed 10 products, every product has 1 to 7 input fields, every input has the name="barrel" attribute.

I use this jquery code to get the inputs values:

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

The problem is that gets the values from all inputs from all products. But I want to get the input values only from the product I pressed Add to Cart.

Please give me an advice. Thanks

Upvotes: 0

Views: 44

Answers (2)

Viktor Maksimov
Viktor Maksimov

Reputation: 1465

If you have the following 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>

You should use this script:

$(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;
    });
});

Upvotes: 1

Aer0
Aer0

Reputation: 3907

You may add a class to every used inputfield and filter by that class. So you would avoid using all inputfields values.

Upvotes: 0

Related Questions