The addClass() and removeClass() functions in Jquery are not functioning correctly

$('.push').each(function(){
  if($(':first-child',this).hasClass( "activex" )){
    $(this).off().off('click').on('click',function(){
      var a = $(this).attr('id');
      $.ajax({
        type: "POST",
        url: "includes/rcart.php",
        data:{'pid': a},
        success: function(data){
          var a= parseInt($('.cart').text());
          if((data.indexOf("2")) >= 0){
            console.log(data);
            console.log('not removed'); 
          }else{
            a--;
            console.log('removed');
            $(this).children().removeClass('activex');
            $('.cart').text(a);
          }
        }
      });
      console.log(a); 
    });
  }else{
    $(this).on('click',function(){
      var a = $(this).attr('id');
      $.ajax({
        type: "POST",
        url: "includes/cart.php",
        data:{'pid': a},
        success: function(data){
          console.log(data);
          var a= parseInt($('.cart').text());
          if((data.indexOf("2")) >= 0){
            console.log('done'); 
          }else{
            a++;
            $('.cart').text(a);
            $(this).children().addClass('activex');
          }
        }
      });
      console.log(a); 
    });
  }
});

I am facing an issue where the code is unable to remove the class activex when a button with the push class is clicked. Strangely, there are no errors in the code and despite removing the class manually in the Chrome Developer Console, the class does not get removed.

Answer №1

Check out the revised code below, where I've made some adjustments by removing the children() method. Feel free to test it out and let me know if it works for you!

$('.push').each(function(){
    if($(':first-child',this).hasClass("activex")){
        $(this).off().off('click').on('click',function(){
            var a = $(this).attr('id');
            $.ajax({
                type: "POST",
                url: "includes/rcart.php",
                data:{'pid': a},
                success: function(data){
                    var a= parseInt($('.cart').text());
                    
                    if((data.indexOf("2")) >= 0){
                        console.log(data);
                        console.log('not removed'); 
                    }
                    else {
                        a--;
                        console.log('removed');
                        $(this).removeClass('activex');
                        $('.cart').text(a);
                    }
                }
            });
            console.log(a); 
        });
    } else {
        $(this).on('click',function(){
            var a = $(this).attr('id');
            $.ajax({
                type: "POST",
                url: "includes/cart.php",
                data:{'pid': a},
                success: function(data){
                    console.log(data);
                    var a= parseInt($('.cart').text());
                    
                    if((data.indexOf("2")) >= 0){
                        console.log('done'); 
                    }
                     else {
                         a++;
                         $('.cart').text(a);
                         $(this).addClass('activex');
                     }
                 }
            });
             console.log(a); 
         });
     }
});

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

Elegant switch in jQuery

I am trying to use jQuery to create an animated toggle button. The toggle function is working correctly, but I am having trouble adjusting the speed and smoothness of the animation. After researching different methods and attempting to modify the values i ...

Import a 3-dimensional object from an .obj file and adjust its positioning within the camera view using Three.js

I am currently working on dynamically loading object files using THREE.OBJLoader and positioning them in the center of the scene or canvas to ensure the entire object is visible in the camera view. Since the objects are dynamic, I do not have fixed height ...

Issue with burger menu functionality, button unresponsive

Two files are involved in this issue, one is a Vue file and the other is a JavaScript file. The JavaScript file contains an array and the problem is being described in the console. Additionally, there may be an issue with items as sometimes the same error ...

How can JavaScript be used to access response header information in Devise Token Auth?

Currently, I am in the process of developing a web application using Rails as the backend API and Vue.js as the frontend library. For authentication purposes, I have integrated the devise_token_auth library. However, I am facing difficulty in retrieving th ...

Give drawn elements a touch of fuzziness and experiment with the color of the fragment shader

I am currently experimenting with creating an animated gradient effect by blending three separate blobs together in a melting-like fashion, with each blob moving independently. The desired result can be seen in the image provided below. So far, I have bee ...

Tracking page views through ajax requests on Google Analytics

I have implemented a method to log page views through ajax action when the inner page content is loaded. However, I am facing an issue where the bounce rate data is not getting updated and always shows 0%. The default Google Analytics page view is logged ...

Setting up pagination for displaying data from a database on the client-side: a step-by-step guide

Greetings to all my fellow programmers on Stack Overflow! I am currently in the process of developing an e-commerce application using JSP. The products for the application are stored in a server-side database (Mysql) within a table named product. The prod ...

Is it possible to exclusively utilize jQuery with ZURB Foundation 4 and exclude Zepto altogether?

I'm currently working on a project that involves incorporating jQuery. I decided to manually include jQuery in ZURB Foundation 4. As part of the process, I removed: <script> document.write('<script src=' + ( ...

Generate an HTML document from a website page

Having difficulty grasping this concept. I am completely lost on where to begin. It is imperative that I determine how my website can generate a file (whether it be HTML or Text format) and enable users to download it, similar to the functionality in Goo ...

Using Jquery to tally the number of JSON elements

I'm currently developing a chart system that pulls data from an AJAX JSON response. My goal is to categorize certain JSON objects based on color and month. For instance, I aim to organize all the colors (Red, Blue, Yellow) into separate groups and th ...

Turn off hover effect using solely CSS

This is my first time posting on stackoverflow, so please excuse me if I overlook something obvious. I tried searching for a solution beforehand but couldn't find one that seemed relevant. In the following jsfiddle example, I have a div that acts as ...

Looking to add a close button to the iFrame, but having trouble getting it to function when clicked

In my project built with Meteor, I have integrated an iframe to display specific content to the user. The iframe is functioning as expected, but I am looking to add a close button that will effectively unload the iframe when clicked. I attempted to imple ...

How to dynamically populate a select option with data from a database in CodeIgniter 3 and automatically display the result in a text

How can I fetch select options from a database in CodeIgniter 3 and display the result in a text field and span area? Currently, I am only able to display data from the row_name when an option is selected. Here is my current implementation: <?php $query ...

Image missing aria-label attribute

I am facing an issue with getting the aria-label to display on my image. Despite checking my code, I cannot figure out why it is not working. Any ideas on what might be missing? Here is the code from my NextJS app: The svg in my public folder. <?xml v ...

Navigating a collection of objects after a button is clicked

My current library project involves looping through an array of objects to display them on a grid based on input values. Here is the code snippet for my loop: const addBook = (ev) => { ev.preventDefault(); let myLibrary = []; let bookIn ...

How can I create a single modal in Ionic 3 that occupies the full screen width and height?

Having trouble resizing my Ionic modal to full screen for just one modal, as Ionic's default settings are overriding any custom changes. I've attempted the following code snippet: @media only screen and (orientation: landscape) { ion-modal { ...

Is the package downloaded through NPM identical to the local file in my particular situation?

In my current project, the previous developers included jQuery in the local environment, and a minified version 3.1.1 has been maintained for the past two years. I am now attempting to manage it using NPM. However, more experienced developers are cautionin ...

Classes that are designed to be written on a single

A fellow team member recently made an addition to our project. <ol class="numbered-list list-inside" start="1"> .numbered-list { list-style-type: decimal; } .list-inside { list-style-position: inside; } Is there a problem with this code, ...

Discovering instances of a specific string within a larger string

My goal is to customize the default behavior of the alert function. Below is the code I am using: window.alert=function(txt) { waitOk='wait'; setMsgBox(txt); btnMsgOk.focus(); } However, I need this functionality to vary ba ...

Preventing Duplicate Form Submissions in Rails 5 using jQuery

As a coding novice, I'm currently working on my Rails 5 app and implementing image cropping and uploading directly to AWS S3 from the client side using blueimp/jQuery-File-Upload. However, I have encountered an issue where multiple form submissions o ...