Tim Mwaura
Tim Mwaura

Reputation: 619

Getting a value within the parent element of a clicked button

I am new to Jquery and I'm trying to access the parent of a clicked button. This is due to the fact that I am generating divs dynamically, so I want the respective button click to apply to the correct div.

After accessing the parent of the clicked button, I want to access several input values within it.
I'm getting an error in the console :[DOM] Found 2 elements with non-unique id #quantity because I have a for loop that produces similar divs with a unique quantity.

I have tried using document.getElementById("onekg").value; But it only works for the first element and not subsequent elements.

    <% cakes.forEach(cake => { %>
        <div class="item-cart">
         <input type="hidden" name="onekg" id="onekg" value="1000">
         <input id="quantity" type="text" name="quantity" value="1">
         <button id="plus_btn" class="plus-btn qbtn" type="button" name="button">+</button>
       </div>
    <% }) %>

JQuery

$(".plus-btn").click(function (event) {
  event.preventDefault();
  event.stopPropagation();
  var currentItem = $(event.target).parents('.item-cart');
  console.log(currentItem);
  var onekg = document.getElementById("onekg").value;
  var quantity = document.getElementById("quantity").value;
  console.log(quantity + onekg)
})

I don't know if I'm thinking about this all wrong but I have tried several solutions without any success.

Upvotes: 2

Views: 3751

Answers (1)

melvin
melvin

Reputation: 2621

You can use the following code

$(".plus-btn").click(function (event) {
    var parent = $(this).closest('.item-cart');
});

The above code will find the item-cart class that is the parent of the button click. So on each click of the button, you can access the parent of that particular clicked button.

So your code would be something like below as per your code.

$(".plus-btn").click(function (event) {
    var parent = $(this).closest('.item-cart');
    var onekg = parent.find("#onekg").val();
    var quantity = parent.find("#quantity").val();
});

But you should be aware that there should not be any Id more than once in a page. So i would suggest you to change onekg and quantity to class and rewrite the code as following

<input type="hidden" name="onekg" class="onekg" value="1000">
<input class="quantity" type="text" name="quantity" value="1">

and change your jQuery code to the following.

$(".plus-btn").click(function (event) {
    var parent = $(this).closest('.item-cart');
    var onekg = parent.find(".onekg").val();
    var quantity = parent.find(".quantity").val();
});

Upvotes: 3

Related Questions