Home > Software engineering >  I have a dynamic html template. Which forms when I click on a button. Now, the problem is When I cli
I have a dynamic html template. Which forms when I click on a button. Now, the problem is When I cli

Time:12-28

Here is the html template forms when I click on a button.

<div >
                    <h3>${element.name}</h3>
                    <p>Phone: ${element.phone}</p>
                    <button onclick="addToHistory()">Call</button>
                </div>`

Let's say it creates two template as it is.

<div >
                        <h3>Person1</h3>
                        <p>Phone: 0111111111</p>
                        <button onclick="addToHistory()">Call</button>
                    </div>`

<div >
                        <h3>Person2</h3>
                        <p>Phone: 0111111111</p>
                        <button onclick="addToHistory()">Call</button>
                    </div>`

Now, I want to click on one button and then according to my click I want the data of clicked divs should store.

I tried this using event handler as you can see with addToHistory() function. But, it stores all the data both I clicked and not clicked also.

Please note: I want to do this only using JavaScript. Thank you for your support.

CodePudding user response:

You can pass this into your method and use that to traverse within the specific detail container where the button was clicked.

this will reference the specific element the event occurs on

function addToHistory(el){
   console.log(el.previousElementSibling.textContent);
}
<div >
  <h3>Person1</h3>
  <p>Phone: 0999999999</p>
  <button onclick="addToHistory(this)">Call</button>
</div>`

<div >
  <h3>Person2</h3>
  <p>Phone: 0111111111</p>
  <button onclick="addToHistory(this)">Call</button>
</div>`

CodePudding user response:

We can trigger button click by class. 
Please check this example `https://jsfiddle.net/h54dt731/`
  • Related