Search code examples
javascripthtmlfunctionsimplecart

How to set Javascript "name" when link is clicked?


When I click the button it preforms a function, I am now trying to make it so name: "", is entered when the button is pressed.

I added name="item1" inside the tag but this does not yield the desired result.

<img onclick="addbeat()" name="item1" src="button.png"/>

<script>
function addbeat() {
simpleCart.add({
     name: "",
     price: .99
 });
}
</script>


Solution

  • Update for clarity

    You have 2 options here. If you're going with an inline event handler, then you can pass an event object to your click handler and access the image that was clicked using event.target, like so:

    <img onclick="addbeat(event)" name="item1" src="button.png"/>
    
    <script>
    function addbeat(event) {
    simpleCart.add({
         name: event.target.name,
         price: .99
     });
    }
    </script>
    

    A preferable option (as pointed out in surrounding discussion) would be to programmatically attach your click handler- at which point you could use either event.target or this.

    <img id="anImage" onclick="addbeat(event)" name="item1" src="button.png"/>
    
    <script>
    function addbeat() {
    simpleCart.add({
         name: this.name,
         price: .99
     });
    }
    
    document.getElementById('anImage').onclick = addbeat;
    </script>