简体   繁体   中英

Uncaught ReferenceError: addToCart is not defined javascript

i am using javascript onclick function to make a function but it returns an error Uncaught ReferenceError: addToCart is not defined i don't know why here is my code

my javascript code

function addToCart(){
  var productname = $('pname').text();
  var productid = $('productid').text();
  var color = $('#color option:selected').text();
  var color = $('#size option:selected').text();
  var quantity = $('#qty').val();
  $.ajax({
    type: "POST",
    dataType: 'json',
    data:{
      color:color,
      size:size,
      quantity:quantity,
      productname:productname,
    },
    url: "cart/data/store"+productid,
    success:function(data)
    console.log(data);
  })

and my onclick input

<input type="submit" class="btn btn-primary" onclick="addToCart()" value="add to cart">

你做了onclick="addToCart()"立即执行你应该onclick="addToCart"的功能。

This is probably happening because the browser isn't properly loading your function. I would try adding a console.log above and outside of your function definition to make sure it's being loaded.

More generally, if you're using jQuery, you probably want to attach that addToCart onclick handler in Javascript rather than in HTML. See this question for more details: Add onclick event to button after document is ready with JS/JQuery selecting by class

In the case of everything is okay then what you can do is insted of onclick in html

<input type="submit" class="btn btn-primary" id="cart-btn" value="add to cart">

Script:

 $(document).ready(function(){
   function addToCart(){
   //function definition
 }
  $("#cart-btn").click(addToCart);
 });

I think your addToCart function is either not loading or not defined in the global scope!

Example 1 (Function defined in global scope)

 function hi() { alert("hi"); }
 <button onclick="hi()">Click Me</button>

Example 2 (onClick function not defined in global scope)

 (() => { function hi() { alert("hi"); } })()
 <button onclick="hi()">Click Me</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM