Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

345
Views
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">
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You did onclick="addToCart()" which immediately executed the function you should onclick="addToCart".

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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);
 });
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!