Handlebar styling issue on each div

Viewed 148

In the below code, I have used handlebars.js for templating in which it creates each donation from the server but the onClick event doesn't affect all the iterated div, it only affects the first div. How to fix such an issue using handlebars.js?

{{#each donations}}
    <div  id="changeCss">
        <h1>Donar name: {{donar}}</h1>
        <h1>Food item:{{fooditems}}</h1>
         <h1>Quantity:{{quantity}}</h1>
        <h1>Meeting point: {{meetingpoint}}</h1>
        <h1>Food type: {{foodtype}}</h1>
        <h1>Contact no: {{contactno}}</h1>
        <button onclick="changed()" id="idOfButton">I will deliver</button>
    </div>
{{/each}}

<script> 
      function changed(){
      document.getElementById('changeCss').style.cssText ='background-color:green; color:white' ;
      document.getElementById("idOfButton").disabled= true;
          
</script>
1 Answers

You're creating many div blocks with the same id changeCss, and
document.getElementById('changeCss') always refer to the first matching div.

I'm assuming you want to change only the div where the button is clicked. 1 solution is to pass the current button as a parameter of the changed function. Then we apply the CSS to the parent element (the div) and disable the current button.

The code below demonstrates what I said for 2 identical blocks. `

 function changed(element){
      // element is the button you clicked
      element.parentElement.style.cssText ='background-color:green; color:white' ;
      element.disabled= true;
 }
  <div  id="changeCss">
        <h1>Donar name: {{donar}}</h1>
        <h1>Food item:{{fooditems}}</h1>
         <h1>Quantity:{{quantity}}</h1>
        <h1>Meeting point: {{meetingpoint}}</h1>
        <h1>Food type: {{foodtype}}</h1>
        <h1>Contact no: {{contactno}}</h1>
        <button onclick="changed(this)" id="idOfButton">I will deliver</button>
  </div>
    
  <div  id="changeCss">
        <h1>Donar name: {{donar}}</h1>
        <h1>Food item:{{fooditems}}</h1>
         <h1>Quantity:{{quantity}}</h1>
        <h1>Meeting point: {{meetingpoint}}</h1>
        <h1>Food type: {{foodtype}}</h1>
        <h1>Contact no: {{contactno}}</h1>
        <button onclick="changed(this)" id="idOfButton">I will deliver</button>
  </div>

Related