2
<div class="panel">
    <div class="panel-heading item-name">T-shirt1</div>
    <div class="panel-body"><img src="img/shirt1.jpg" class="img-responsive" alt="Image"></div>
    <div class="panel-footer text-center">
        <h5>PRICE: <span class="old-price">$15.32</span></h5>
        <h4>$17.56</h4>
        <button type="button" class="btn btn-danger add-to-cart">Add to cart</button>
    </div>
 </div>
<div class="panel">
    <div class="panel-heading item-name">T-shirt2</div>
    <div class="panel-body"><img src="img/shirt2.jpg" class="img-responsive"  alt="Image"></div>
    <div class="panel-footer text-center">
        <h5>PRICE: <span class="old-price">$21.67</span></h5>
        <h4>$23.15</h4>
        <button type="button" class="btn btn-danger add-to-cart">Add to cart</button>
    </div>
</div>
<div class="panel">
    <div class="panel-heading item-name">T-shirt3</div>
    <div class="panel-body"><img src="img/shirt3.jpg" class="img-responsive" alt="Image"></div>
    <div class="panel-footer text-center">
        <h5>PRICE: <span class="old-price">$16.69</span></h5>
        <h4>$16.80</h4>
        <button type="button" class="btn btn-danger add-to-cart">Add to cart</button>
    </div>
</div>

What I really want is to retrieve the value of each item-name when I click on the Add to cart button. If I click on the first button, I should get T-shirt1, second button should alert T-shirt2, third button => T-shirt3.

Here is my jQuery script.

<script>

$('.add-to-cart').click(function() {
    var itemName = $('.item-name', this).text();
    alert(itemName);
}); 
</script>

2 Answers 2

3

You can try this:

$('.add-to-cart').click(function() {
    var itemName = $(this).closest('.panel').find('.item-name').text();
    alert(itemName);
}); 

Usage of the closest method: closest

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your quick answer. Does exactly what I wanted.
1

Go from clicked button up in parents chain until you find .panel and then down in children tree until you find .item.name:

$('.add-to-cart').click(function() {
    var itemName = $(this).parents('.panel').children('.item-name').first().text();
    alert(itemName);
}); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.