Home > database >  how to put the item id on console.log using add to cart button using javascript?
how to put the item id on console.log using add to cart button using javascript?

Time:08-22

This is my html button for add to cart and below that is the JavaScript code I am using to display the itemdetails id into the browser console of google chrome.

 {% for detail in tonerdetails %}

      <tr>
          <td>{{detail.toner_model.toner_model}}</td>

          <td>{{detail.issued_to.name}}</td>
          <td>{{detail.employee_name}}</td>
          <td>{{detail.employee_designation}}</td>
          <td>{{detail.status}}</td>
          <td><a href="{% url 'print_toner_issue_vouchers' detail.id %}" target="_blank" rel="noopener noreferrer" >Print Issue Voucher</a>
              <a href="{% url 'print_toner_sent_invoice' detail.id %}" target="_blank" rel="noopener noreferrer" >Print Invoice</a>

              <a data-detail="{{detail.id}}" data-action="add" >Add to Cart</a>
              <a href="{% url 'edit_tonerdetails_form' detail.id %}" >Edit</a>
              <a data-toggle="modal" data-target="#delete-modal{{ toner.pk }}" >Delete</a></td>
      </tr>

let butns=document.getElementsByClassName('addtocart')
for (btn of butns){
    btn.addEventListener('click', function(){
        let detailid=this.dataset.detail
        let action=this.dataset.action
        console.log(detailid)
    })
}

CodePudding user response:

There was a typo inside your JavaScript you were listening event on butns array not on each element of that array so I changed it to btn.addEventListener and it should be

let action=this.dataset.action

instead of

let action=this.dataser.action

Here is working example

let butns=document.getElementsByClassName('addtocart')
for (let btn of butns){
    btn.addEventListener('click', function(){
        let detailid=this.dataset.detail
        let action=this.dataset.action
        console.log(detailid)
    })
}
<table>
<tr>
<a data-detail="1" data-action="add" >
Add to Cart - 1
</a>
</tr><br>
<tr>
<a data-detail="2" data-action="add" >
Add to Cart - 2
</a>
</tr><br>
<tr>
<a data-detail="3" data-action="add" >
Add to Cart - 3
</a>
</tr>
</table>

Update

Turns out above solution is not working for you here is one more approch to solve your problem

function getCartData(detailId, action){
  console.log(detailId)
  console.log(action)
}
<table>
<tr>
<a onclick="getCartData(1, 'add-one')" >
Add to Cart - 1
</a>
</tr><br>
<tr>
<a onclick="getCartData(2, 'add-two')" >
Add to Cart - 2
</a>
</tr><br>
<tr>
<a onclick="getCartData(3, 'add-three')" >
Add to Cart - 3
</a>
</tr>
</table>

in above example you've to pass your getCartData('{{detail.id}}', 'add')

  • Related