P. Lau
P. Lau

Reputation: 165

alert value of button by onClick

I have a page with a lots of buttons from PHP output with each buttons having different values:

<button class='add' value=".$row['cat_no']." onClick='addItem(value)'>Add To Cart</button>

$row['cat_no'] is data from mysql. 

I want to check the button's value when I click it, so I use native JS below:

<script>
function addItem(value) {
            alert("this.value");}
</script>

It is not working...it just return this.value. In this case I don't think it is suitable to assign Id to getElementbyId, Pls help to check my mistake or suggest solution. Thanks.

Pls: I dont want to use JQUERY, just native JS.

Upvotes: 2

Views: 8208

Answers (3)

Allan Chua
Allan Chua

Reputation: 10175

the code below helps you retrieve the value of the element that triggered the event:

<button class='add' value="test value" onClick='addItem(this)'>Add To Cart</button>

<script>
  function addItem(sender) {
        alert(sender.value);
  }
</script>

However, this is filled with code smells.

I would suggest doing the code below

    <button id='add-to-cart' class='add' value="test value">Add To Cart</button>

On a separate JS file:

(function() {
    function _onLoad() {
        var addToCartButton = document.getElementById("add-to-cart");

         addToCartButton.addEventListener("click", _onAddToCartClicked);
    }

    function _onAddToCartClicked() {
        var sender = this;

        alert(sender.value);
    }

    document.addEventListener("DOMContentLoaded", _onLoad, false);
})();

This approach ensures that:

  1. Concerns are separated between HTML and JS
  2. External JavaScript file would be cached which results to faster page load time.
  3. UI would render faster since there are no inline scripts
  4. Global namespace won't be polluted

Upvotes: 3

P.S.
P.S.

Reputation: 16384

You don't really need this in your function, just use value. And also remove double quotes, because you need to alert function's parameter, not string, like this:

function addItem(value) {
  alert(value);
}

Here is the working example:

function addItem(value) {
  alert(value);
}
<button class='add' value="yourValue" onClick='addItem(value)'>Add To Cart</button>

Or you can pass the element to function using this, and then get the needed attribute value from addItem method:

function addItem(item) {
  alert(item.value);
}
<button class='add' value="yourValue" onClick='addItem(this)'>Add To Cart</button>

Upvotes: 0

jafarbtech
jafarbtech

Reputation: 7015

Use alert(elmt.value); like below. you should pass this to the function

<button class='add' value="test value" onClick='addItem(this)'>Add To Cart</button>

<script>
function addItem(elmt) {
            alert(elmt.value);
            }
</script>

Upvotes: 4

Related Questions