Reputation: 21
I am creating a shopping cart with same Addtocart button on each row. as shown in the below table
I used a for loop to print each row. I want to access the data of a row in which the button is clicked. How can i do it?
Upvotes: 0
Views: 452
Reputation: 21
As @nice_dev said, you could add a custom data attribute to the buttons and access it onclick or even just traverse the html using the this keyword:
function myFunction1(data){
console.log(data)
}
function myFunction2(element){
console.log(element.parentElement.children[0].innerText)
}
<!-- HTML traversal inline-->
<div>
<p>Galaxy Note S7</p>
<button onclick="myFunction1(this.parentElement.children[0].innerText)">Buy</button>
</div>
<!-- HTML traversal in JS Function-->
<div>
<p>Galaxy Note S8</p>
<button onclick="myFunction2(this)">Buy</button>
</div>
<!-- Data Tag (attribute could be retieved from JS also)-->
<div>
<p>Galaxy Note S9</p>
<button data-device="Galaxy Note S9" onclick="myFunction1(this.getAttribute('data-device'))">Buy</button>
</div>
Upvotes: 1