Sridhar Reddy
Sridhar Reddy

Reputation: 21

How to get row data when clicking button which is inside a row using javascript?

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

Answers (1)

somebody32x2
somebody32x2

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

Related Questions