The functionality of a generated button has been compromised

My goal is to create a webshop that doesn't rely on MySQL or any database, but instead reads items from JSON and stores them in LocalStorage. However, I've encountered an issue where the functionality of buttons gets lost after using AJAX to generate new "Add to Cart" buttons.

    function load(){
    let listLoad = "";
    for (var i = 0; i < localStorage.length; i++) {
    var keyLS = JSON.parse(localStorage.getItem(localStorage.key(i)));
    listLoad += `<tr>
                 <span id="thisID" style="display:none">${keyLS.id}</span>
                 <td>${keyLS.name}</td>
                 <td>${keyLS.price}</td>
                 <td>${keyLS.quantity}</td>
                 <td><button type="submit"id="addOne" class="btn btn-success addOneItem">+</button></td>
                 <td><button class="btn btn-danger removeOneItem">-</button></td>
                 </tr>`

                }
     if(listLoad != ""){
         $("#cleanCart").css("display","inline");

     }
     document.getElementById('itsTboDy1').innerHTML = listLoad;
}

Above, you'll find the AJAX script that loads items from a JSON file.

$(function(){
 $(".addOneItem").click(function(){

     console.log("lol");
 })
})

Unfortunately, this button functionality only works once, right after the page is loaded.

Answer №1

This particular method

$(function(){
 $(".addOneItem").click(function(){

     console.log("lol");
 })
})

The purpose of this function is to attach event listeners to all instances of .addOneItem within the document object model (DOM) when it is called. If any new .addOneItem buttons are dynamically added to the DOM using a function like load(), it becomes essential to also ensure that event listeners are bound to these newly created elements. Furthermore, without viewing the HTML code, it can be assumed that the original button was nested within the #itsTboDy1 element and that the load() function replaced its content, thereby removing the previous elements along with their associated event listeners.

Answer №2

It appears that your button is being loaded dynamically, which means the .click event may not work properly for these elements. I recommend trying the .on method instead, which would look something like:

$(function(){
 $(document).on("click",".addOneItem",function(){

     console.log("lol");
 });
});

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

What are the steps to incorporate client-side JavaScript into ASP.NET using AJAX technology for programming?

I have the knowledge of ASP.NET and I want to create a website using it in the server side, along with JavaScript (possibly jQuery) in the client side, utilizing Ajax technology. There are rumors that ASP.NET AJAX is slow. If this is true, what other opt ...

Creating dynamic routes in express.js with fixed components

I'm exploring how to create a route in express that captures URLs like this: /events/0.json Here's what I've attempted so far (but it's not working as expected): router.put('/events.json/:id.json', isLogged, events.update) ...

Having trouble sending a request in next.js with Docker during the build process?

When utilizing the getStaticProps function to send a request to my backend API from another Docker container, I am encountering an issue. Despite ensuring that the API URL is accurate, the static page fails to be created. This is due to the requirement for ...

Struggles with converting Atom to JSONP

Currently, I am working on a news feed that is hosted on a separate server where the static PDF documents referenced in the feed are stored. I am exploring the possibility of implementing client-side feed parsing since I am uncertain about the capabilitie ...

"Enhancing ASP.NET localization through the implementation of Page Methods and Web Services using AJAX

It's quite complicated... We are facing an issue with client-side validation through AJAX calls to page methods, acting as web services. Additionally, we have implemented a drop-down menu for language selection and a class that extends Page to handle ...

Using an Ajax Post Call to send FormData leads to a Get request instead

Having trouble with sending a simple form via POST method. I load the form content using AJAX: $(function() { var arg = { "operation": "upload", "step": "0" ...

Beware, search for DomNode!

I attempted to create a select menu using material-ui and React const SelectLevelButton = forwardRef((props, ref) => { const [stateLevel, setStateLevel] = useState({ level: "Easy" }); const [stateMenu, setStateMenu] = useState({ isOpen ...

Tips for efficiently loading data into a vuex module only when it is required and addressing issues with async/await functionality

Is there a method to load all the data for a Vuex store once and only load it when necessary? I believe there is, but I am having trouble implementing it. I'm not sure if it's due to my misunderstanding of Vuex or Async/Await in Javascript promi ...

Dynamic Styling in Angular 2/4: A Modern Approach

Can someone help me with Angular 2/4 syntax for this code snippet? $('nav ul li a').click(() => { $(this).closest('li').addClass('active'); }); ...

Encountering an undefined property error when parsing JSON data

Trying to parse JSON values using PHP. Everything works fine, but the subsequent arrays are not getting printed and instead, I am getting an undefined property error. The first array displays easily. Following but modified as per requirements. Please poi ...

Executing Javascript code that has been retrieved using the XMLHttpRequest method in a

Would it be feasible to modify this code to function recursively if the redirects to the js file that needs to be executed? function loadScript(scriptUrl) { var xhr = new XMLHttpRequest(); xhr.open("GET", scriptUrl); xhr.onready ...

What is the process for transforming the result of a .aspx file into a JSON format?

I am trying to convert the output of an .aspx page into a JSON object in order to accommodate a JSONP Ajax request. Here is what's happening on the page: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="mypage.aspx.cs" Inherits="folder_myp ...

Navigate directly to the section on the page that discusses the hashtag

So, I have a unique scenario to address. I'm working with two div elements where only one should be visible at a time. Here's the situation: The first div serves as an introduction page with a button that hides it and reveals the second div. Th ...

Retrieve the thousand separator for numbers using Angular in various languages

When using the English locale, numbers appear as follows: 111,111,222.00, with a comma as the thousand separator and a point as the decimal separator. In languages like German, the same number would be represented as 111.111.222,00, reversing the positions ...

Utilize unshift() method in JavaScript to insert form input into an array

I'm having trouble with adding elements to an array using a form and the unshift() method. The code snippet provided below isn't functioning as expected, and I need help understanding why. <form> <input id="input"></input> < ...

Visual Studio - TypeScript project synchronization issue

Currently using the 2015 version of Visual Studio Community, I am facing an issue while working on a typescript project. Whenever I make modifications to the code, debug it, and save it using ctrl + s followed by refreshing the browser with ctrl + r, the c ...

What steps should I take to handle and utilize a JSON request that is expected to be improperly structured?

My current project involves setting up a system where I receive a POST request that then triggers another POST request. The issue is that the incoming request has a Content-Type of application/json, but the body data appears to be incorrectly formatted JSO ...

Other browsers, such as Chrome and Firefox, are visible, except for Safari

https://testing007.s3-api.us-geo.objectstorage.softlayer.net/1A23CDC6F75811E6BFD706E21CB7534C---prof__6.jpg This link displays correctly on browsers like Chrome and Firefox, but does not show up on Safari. ...

Footer refusing to stay fixed at the bottom of the viewport

Currently, I am utilizing fullpage.js with scrolloverflow.js activated on the second section. In this setup, I would like to have a footer that remains fixed at the bottom of the viewport for the second section only. However, instead of achieving this desi ...

Sending variables with spaces to the curl --data parameter

When dealing with arguments that contain spaces, it's important to note that they may not pass correctly to the curl command. Additionally, quotes might not be properly transferred in the --data field. For example, if I simply echo the variable &apos ...