0

im a beginner on Javascript , i have 3 button ADD TO CART each one has a value , so when i click on one of them , i keep getting the value of first button this is my HTML CODE

<div class="container main-section">
              <div class="row">
                <div class="col-md-4 col-sm-4 col-xs-12 product">
                  <div class="row product-part">
                    <div class="col-md-12 col-sm-12 colxs-12 img-section">
                      <img src="'. $photolink["photo"] .'">
                    </div>
                    <div class="col-md-12 col-sm-12 col-xs-12 product-title">
                      <h1>'. $row["produit"] .'</h1>
                    </div>
                    <div class="col-md-12 col-sm-12 col-xs-12 product-description">
                      <p>'. $row["description"] .' </p>
                    </div>
                    <div class="col-md-12 col-sm-12 col-xs-12 product-cart">
                      <div class="row">
                        <div class="col-md-6 col-sm-12 col-xs-6">
                          <p>'. $row["price"] .' $</p>
                        </div>
                        <div class="col-md-6 col-sm-12 col-xs-6 text-right product-add-cart">
                          <input type="submit"  value="ADD TO CART" class="btn btn-success" id="productid" data-value="'. $row["id"] .'" onclick="getID()" >
                        </div>
                      </div>
                    </div>
                  </div>
                </div>

this is my javascript code

function getID()
{
var val = document.getElementById('productid').getAttribute('data-value');
console.log(val);
}
clackj
  • 13
  • 6
  • 3
    When you say 'I have 3 items' do you mean three `input` elements with the same `id` of `productid`? If so, that's your problem. `id` attributes need to be unique within the DOM – Rory McCrossan Feb 23 '18 at 15:31
  • yes all of them same id – clackj Feb 23 '18 at 15:35
  • Use classes instead. You can select the elements by `getElementsByClassName()` or `querySelectorAll()`, but note that you'll need to loop through them to get their values – Rory McCrossan Feb 23 '18 at 15:36

1 Answers1

1

You must select an element specificly. Using pure JQuery:

function getID(that) {
  console.log($(that).attr("data-value"));
}

Then on your HTML:

<input type="submit" value="ADD TO CART" class="btn btn-success" id="productid" data-value="'. $row["id"] .'" onclick="getID(this)">
Luicy
  • 23
  • 1
  • 14