Vic
Vic

Reputation: 29

Onclick cannot find function to execute

I am using an onclick() function to add an item to cart.

<button class='btn pull-right' id = 'cartBtn' onclick = 'addToCart(<?php echo $id;?>)'><span class='glyphicon glyphicon-shopping-cart'></span></button>

This is the js:

$(document).ready(function(){
    var cart = [];
    var id = $("#itemId").text();
    var stockAvailable = $("itemStock").text();
    var inCart = false;


    function addToCart(item){
        id = item;
            if (inCart == true){
                console.log("item already in cart");
            }
            else{
                cart.push(id);

            }

    }

However, I get the following error in the console upon clicking the button:

ReferenceError: addToCart is not defined

I have written the js code on a separate file and inluded it in the head section. What could be the problem here

Upvotes: 1

Views: 1056

Answers (4)

Jwngsat Narzary
Jwngsat Narzary

Reputation: 21

You cannot use addToCart without defining it. You can define it in the place where you want to use this function.

$(document).ready(function() {
  function addToCart(item) {
    console.log('added');
  }
});
addToCart('item');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Right way

function addToCart(item) {
  console.log('added');
}
$(document).ready(function() {

});
addToCart('item');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 2

Shivaji Kokate
Shivaji Kokate

Reputation: 37

Anyways you are using Jquery, so can you please check with jquery event handler.

Please find the answer using jquery click event.

$("#cartBtn").on("click", function(item){
       id = item;
            if (inCart == true){
                console.log("item already in cart");
            }
            else{
                cart.push(id);

            }
        }
   })

Upvotes: 0

kcsujeet
kcsujeet

Reputation: 522

from the official jquery docs. https://learn.jquery.com/using-jquery-core/document-ready/

TLDR: document.ready runs only once so define your function outside of it.

Upvotes: 1

Ankur
Ankur

Reputation: 516

Here i am showing you very basic example code based on your question

var id, cart = [], stockAvailable, inCart = false;
$(document).ready(function(){
  id = $("#itemId").text();
  stockAvailable = $("itemStock").text();
});

function addToCart(item){
  id = item;
  if (inCart == true){
      console.log("item already in cart");
  }
  else{
      cart.push(id);
      inCart = true;
      console.log("item added in cart");
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class='btn pull-right' id = 'cartBtn' onclick = 'addToCart(1)'><span class='glyphicon glyphicon-shopping-cart'></span> Add to Cart</button>

Upvotes: 1

Related Questions