What's the deal with toggleClass() not functioning properly?

I am facing an issue with a simple class toggle in jQuery. Despite my best efforts, it is not working as intended.

The expected behavior is to toggle the class of the <p> when clicking anywhere on the label. It does work correctly if the checkbox is clicked. However, clicking anywhere else does not trigger the toggle.

$('.xtrag p').on('click', function() {
  $(this).toggleClass('row9');
});
.xtrag {
  margin: 40px;
}
p {
  margin: 10px 0;
}
.row0 {
  background: #eee;
  padding: 4px 8px;
}
.row9 {
  background: #ffd;
}
.rt {
  float: right;
}
label {
  display: inline-block;
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="xtrag">
  <p class="row0">
    <label for="xg1">
      <span class="rt">
            <input type="checkbox" name="extrag[]" value="1" id="xg1" />
          </span>
      Item 1
    </label>
  </p>
  <p class="row0">
    <label for="xg2">
      <span class="rt">
            <input type="checkbox" name="extrag[]" value="2" id="xg2" />
          </span>
      Item 2
    </label>
  </p>
  <p class="row0">
    <label for="xg3">
      <span class="rt">
            <input type="checkbox" name="extrag[]" value="3" id="xg3" />
          </span>
      Item 1
    </label>
  </p>
</div>

What could be causing this issue?

Is there a solution to toggle the class of the <p> when the label is clicked?

I have attempted targeting the <label> and using .parent(), but it has not altered the behavior.

Answer №1

When the input element bubbles up the click event, it triggers two event calls instead of just one.

One solution is to prevent the input from bubbling up, while another approach is to verify the event target:

$('.xtrag p').on('click', function(e) {
  if (typeof $(e.target).attr('type') !== 'undefined') {
    $(this).toggleClass('row9');
  }
});
.xtrag {
  margin: 40px;
}
p {
  margin: 10px 0;
}
.row0 {
  background: #eee;
  padding: 4px 8px;
}
.row9 {
  background: #ffd;
}
.rt {
  float: right;
}
label {
  display: inline-block;
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="xtrag">
  <p class="row0">
    <label for="xg1">
      <span class="rt">
            <input type="checkbox" name="extrag[]" value="1" id="xg1" />
          </span>
      Item 1
    </label>
  </p>
  <p class="row0">
    <label for="xg2">
      <span class="rt">
            <input type="checkbox" name="extrag[]" value="2" id="xg2" />
          </span>
      Item 2
    </label>
  </p>
  <p class="row0">
    <label for="xg3">
      <span class="rt">
            <input type="checkbox" name="extrag[]" value="3" id="xg3" />
          </span>
      Item 1
    </label>
  </p>
</div>

Answer №2

Experiment with the checkbox change instead. The label triggered an additional click.

$('.extras input').on('change',  function() {
  $(this).closest("p").toggleClass('row9');
});
.extras {
  margin: 20px;
}
p {
  margin: 5px 0;
}
.row0 {
  background: #f0f0f0;
  padding: 6px 10px;
}
.row9 {
  background: #ffcccc;
}
.rt {
  float: right;
}
label {
  display: inline-block; 
  width: 100%;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<div class="extras">
  <p class="row0">
    <label for="ext1">
      <span class="rt">
            <input type="checkbox" name="extras[]" value="1" id="ext1" />
          </span>
      Option 1
    </label>
  </p>
  <p class="row0">
    <label for="ext2">
      <span class="rt">
            <input type="checkbox" name="extras[]" value="2" id="ext2" />
          </span>
      Option 2
    </label>
  </p>
  <p class="row0">
    <label for="ext3">
      <span class="rt">
            <input type="checkbox" name="extras[]" value="3" id="ext3" />
          </span>
      Option 3
    </label>
  </p>
</div>

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

How to Use CSS to Align an Image in a Header

I'm struggling to position an image on the top right corner of my page, specifically in the header. Despite searching for help on Stack Overflow and other online resources, I can't seem to figure it out. Currently, here is what I have: https://i ...

Adaptable Design - Concealing Facebook Page Plugin at Specific Screen Widths

Can someone help me figure out how to hide the Facebook page plugin on my website? I tried using CSS but it doesn't seem to be working. Here is the code snippet: @media only screen and (max-width:800px){ .fb-page{ visibility: hidden; } This is t ...

Loop through JSON data using jQuery for parsing

Here is the code snippet I have included below, which is a part of a larger code base: <html> <head> <style> #results{margin-top:100px; width:600px; border:1px solid #000000; background-color:#CCCCCC; min-height:200px;} </style> & ...

Error: The function $(...) does not contain a progressbar

I encountered a TypeError saying $(...).progressbar is not a function when loading the Gentelella - Bootstrap Admin Template Page. This error is affecting many jQuery processes. How can I resolve this? Error in my Code: (custom.js) // Progressbar if ($( ...

Cloning jQuery with varied PHP array value

So, I have the given PHP values: PHP: <?php $names = array("Mike","Sean","Steve"); ?> <script type="text/javascript"> var name_data = <?php echo json_encode($names); ?>; </script> <div class="container"> <div cl ...

Is there a native function in jQuery for conducting long polling?

Currently, I am in the process of developing a Java chat application. Upon initializing my application, I plan to execute the pingAction() function through external jQuery. I referred to this site for guidance on implementing long polling with JQuery - ...

The li elements in a horizontal menu all have equal spacing between them, filling the width of the ul

I designed a horizontal menu navigation system using HTML elements ul for the main menu container and li for menu list items. The layout is structured with display table for ul and table-cell for li. However, I encountered an issue where there are inconsis ...

The usage of $('').switchClass in IE8 may cause an error when the switched class includes a color property

I have the following unique css classes .swap-format{ background-color: green; } .swap-format1{ background-color: orange; } .swap-format2{ color: purple; } Using these classes, I want to create an animation on the given div <div id="swap-clas ...

Having trouble formatting an AJAX POST request properly

Despite my best efforts, I continue to encounter the dreaded 500 (Internal Server Errors) every time I try to execute a POST request to https://rates.tradelanes.us/bankaccount/record/create. I suspect it has something to do with the format of my data. Howe ...

Is it a good idea to show a loading image for slow php/mysql results?

I need some help with my website that is powered by php/MySQL for querying and displaying results. The database has grown to over 40,000 records, causing the query to slow down. I am looking for an efficient way to show a loading image while the page loads ...

Using div elements to mimic the layout of tables with row spans

<div class="container"> <div class="box1">1</div> <div class="box2">2</div> <div class="box3">3</div> </div> .box1 { border: 1px solid red; float: left; width: 20px; } .box2, .box3 { ...

How can I use an ajax get request to retrieve a css file from a webpage and then customize the default styles in my program?

Here is my current code snippet: HTML: <h1>Test Message</h1> Default CSS: h1{ font-size: 24px; } Jquery: $(document).ready(function(req, res){ $.ajax({ url:"example.com/test.css", type : "GET", crossDomain ...

Having issues with Tailwind classes not being applied properly on dynamically generated pages in Gatsby-node

Currently, I am working on building dynamic pages using gatsby-node. The templates for these pages are stored in the templates/ directory. However, I have run into an issue where I cannot utilize tailwind classes within these templates unless they are al ...

How can I incorporate checkboxes and crosses for validation in AngularJS?

I've been searching through the documentation for angularjs and online resources, but I can't seem to find any information regarding a specific aspect of form validation. You know when you input something in a form field (like a name, phone numbe ...

What is the method to include additional value in the User-Agent header for a .ajax request?

My goal is to develop a Chrome plugin that retrieves information from multiple pages, some of which are behind a load balancer requiring a specific user agent code for proper routing. I am currently using an .ajax() call and have experimented with differe ...

How to create a WordPress sidebar that remains fixed while scrolling

I have a WordPress website with a right sidebar that I want to make sticky while scrolling up and down. I applied some CSS styles to achieve this, and now the sidebar is sticky. However, the issue is that it keeps shifting its position from right to left. ...

What is the best way to perform a cross-domain Ajax request to a remote server by utilizing a local PHP file as a

I am facing a challenge where I need to update data in a RDF graph by making a POST call. When I attempt to do this using Ajax in jQuery directly, I receive a console warning stating 'No 'access-control-allowed-origin' ecc.ecc.' However ...

How can a controller configure an AngularJS provider by passing options?

How can I pass configuration options to a provider from a controller? Below is an example of how to pass options/configurations to a provider from the controller: provider.js file: app.provider('contactProvider', function() { this.name ...

Arrange the elements within the anchor tag in a vertical line using Angular Material

Is there a way to style the elements within an anchor tag in Angular Material so that they display in a single line? I am looking for the CSS solution to achieve this outcome. This is my current HTML code: <a mat-list-item [routerLink]="['das ...

jQuery.get() function is limited to specific types of webpages

I have successfully combined multiple weather APIs on my website, which can be found here. Recently, I started using the weather.gov API and it has been quite effective. However, there are certain data points that I need to extract which the weather.gov A ...