JavaScript is experiencing an error where it cannot define a function, rendering it unable to generate a JSON object due to its inability to recognize that the

I've created a JavaScript script function that holds cart items for ordering food. This function takes two parameters: ID and price.

Here is a snippet of my script file:

<script>
    function addtocart(mitem, mprice) {
            var price = String(mprice)
            var mobj = { String(mitem): price }

            var storeobj = JSON.stringify(mobj)
            localStorage.setItem('cart', storeobj)
        }
</script>

My button looks like this:

<p style="position: absolute; bottom: 0px"><button class="button" style="width: 200px" onclick="addtocart( '{{M.Menu_Item}}', '{{M.Menu_ItemPrice}}' )" >Add to Cart</button>

However, when I click on the button in Chrome developer console, it says that the addtocart function is not defined.

I've looked into using onclick listeners, but I need to pass different parameters for each button click. What could I be doing wrong?

Answer №1

Ensure to use square brackets [ ] when setting mobj.

var mobj = { [String(mitem)]: price };

Essentially, Chrome is displaying "Uncaught SyntaxError: Unexpected token :" for

var mobj = { String(mitem): price }  

This error indicates that your JS code is not being recognized due to a syntax issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Finding all parent IDs from a given child ID within a nested JSON structure that contains children can be achieved by recursively

function loadKendoTreeView() { if ($("#treeview").data("kendoTreeView") != null) { $("#treeview").data("kendoTreeView").destroy(); $("#treeview").empty(); } var jsonData = [{ "Id": "239297d8-5993-42c0-a6ca-38dac2d8bf9f", ...

Is it possible to install the lib ldap-client module in node.js?

I'm having trouble installing the lib ldap-client package in Node.js. To try and solve this issue, I consulted the following page: https://github.com/nodejs/node-gyp. In an attempt to fix the problem, I have installed python, node-gyp, and Visual St ...

Automated Desk: adjust page through programming

I am currently utilizing Smart Table and I would like to automatically navigate to a specific page once the controller has been created and the table is displayed. After searching on stackoverflow, I came across this code snippet that allows me to achieve ...

Experiencing the 'Rich Embed fields cannot be empty' error even though my code is functioning properly

My code is set up to log when someone edits a message on Discord. It captures the original message, the edited message, the channel, and more details. Everything seems to be working fine, but I keep encountering an error indicating that my RichEmbed fields ...

Having trouble displaying a table accurately in React

My goal is to create a table with Material UI in React, similar to the one shown in this image: https://i.stack.imgur.com/QIV8o.png Below is the code I have written so far for this table: return ( <> <div className="main-wrapper& ...

"Performing a series of getJSON requests with a delay between each call, iterating through an array

Could someone shed light on why my jQuery/JavaScript code runs with an unexpected flurry of ajax calls instead of at a steady 1-per-second rhythm? var i = 0, l = data.length; function geocode() { $.getJSON( 'https://maps.googleapis.com/maps/api ...

Implementing server-side validation measures to block unauthorized POST requests

In my web application using angular and node.js, I am in the process of incorporating a gamification feature where users earn points for various actions such as answering questions or watching videos. Currently, the method involves sending a post request t ...

I continuously encounter an issue in Vite version 3.2.4 where an error pops up stating `[vite:esbuild] The service has stopped running: write EPIPE`

When I finished creating a Vite app, I ran the command npm run dev and encountered the following error: [vite:esbuild] The service is no longer running: write EPIPE https://i.stack.imgur.com/MZuyK.png I need help solving this error. Can anyone provide gu ...

What is the best way to ensure all requests have been completed before proceeding?

Is there a way to ensure that the sortOrder function only runs once the getOrders function has fully completed its execution? I have considered using a callback, but I am unsure of how to implement it. Do you have any suggestions on how I can achieve this ...

The React application is experiencing difficulty in rendering SVG images exclusively on Windows operating systems

My react app runs smoothly on OSX, but encounters issues on Windows due to SVG files: Module parse failed: Unexpected token (2:0) You may need an appropriate loader to handle this file type. <svg xmlns="http://www.w3.org/2000/svg" viewBox="..."> I ...

Conceal content after a specific duration and display an alternative in its position, continuously repeating the loop

Imagine creating a captivating performance that unfolds right before your eyes. Picture this: as soon as the page loads, the initial text gracefully fades away after just three seconds. In its place, a mesmerizing animation reveals the second text, which ...

Limit the length of text using jQuery by specifying the maximum pixel width

Trying to utilize jQuery for a quick function that calculates the pixel width of a string on an HTML page and then shortens the string until it reaches a desired pixel width... Unfortunately, I'm encountering issues with this process as the text is n ...

Unexpected alteration of property value when using methods like Array.from() or insertAdjacentElement

I'm encountering an issue where a property of my class undergoes an unintended transformation. import { Draggable, DragTarget } from '../Models/eventlisteners'; import { HeroValues } from '../Models/responseModels'; import { Uti ...

Continuously performing a task in Node.js every 2 minutes until a JSON file, which is being monitored for changes every few seconds

In order to modify a process while my program is running, I need to manually change a value in a .json object from 0 to 1. Now, I want the program to: periodically check the .json file for changes. refresh a browser page (using puppeteer) every 2 minutes ...

Utilizing Typeahead for Autocomplete in Durandal: A Step-by-Step Guide

I am attempting to implement an autocomplete input field with typeahead (Twitter Bootstrap) in a modal, but I am encountering difficulties making it function properly. Additionally, this autocomplete field needs to be observable with Knockout so that selec ...

Achieving the status code with the requests library during Django testing: A guide

Currently, I am in the process of developing test cases for my Django application. To retrieve the status code and implement the assert statement, I am utilizing the requests package in Python. It is vital to note that this specific test case pertains sole ...

Is there a way for me to identify when I am "traveling" along the same path?

I want to create a toggle effect where a view is hidden if the user tries to revisit it. This can be useful for showing/hiding modal boxes. Here's the code I attempted: /* Root Instance */ const app = new Vue({ router, watch: { '$route&a ...

Capture the 'value' of the button when clicked using ReactJS

I'm generating buttons dynamically using the map function to iterate through an array. Each button is created using React.createElement. ['NICK', 'NKJR', 'NKTNS'].map(function (brand) { return React.createElement(' ...

What are the differences in how a link tag responds on mobile devices?

I have a question regarding opening a pdf in an iframe on the current page. Is there a way to handle this differently for mobile/tablet users? For example, clicking the link could open it in another tab for better readability instead of within the iframe ...

attempting to fulfil a promise through a resolution

I am currently attempting to use a resolve with a promise in response to an issue with filters that I am currently tackling. However, my resolve function is not yet functioning as expected. I have decided to implement this approach based on advice I recei ...