How can I select the specific element within a class when a particular checkbox is selected?

Having a dynamically generated list of elements, each structured like this:

<div class="under-item-description">
  <span class="under-compare-price">100</span><span class="under-price">50</span>
  <span class="under-compare-price-2">200</span><span class="under-price-2">100</span>
  <div class="under-quantity">
      <label class="under-quantity-button">
        <input type="radio" checked="checked" name="quantity-1" class="under-quantity-radio" value="1"/>
      </label>
      <label class="under-quantity-button">
        <input type="radio" name="quantity-2" class="under-quantity-radio" value="2"/>
      </label>
  </div>
</div>

The number of .under-item-description divs displayed on the page may vary. Currently, four instances are visible.

My goal is to show the .under-compare-price and .under-price when the user selects the first checkbox (name="quantity-1") within a specific .under-item-description div, while hiding .under-compare-price-2 and .under-price-2.

If the second checkbox (name="quantity-2") is selected, then .under-compare-price-2 and .under-price-2 will be shown, while .under-compare-price and .under-price will be hidden in that particular .under-item-description div.

This is my current JavaScript code:

$('.under-quantity-button').click(function(){
  $('.under-quantity-radio').each(function(){
    if($(this).is(':checked')){
        $('.under-compare-price:eq('+$(this).parents('.under-item-description').index()+'), .under-price:eq('+$(this).parents('.under-item-description').index()+')').show();
        $('.under-compare-price-2:eq('+$(this).parents('.under-item-description').index()+'), .under-price-2:eq('+$(this).parents('.under-item-description').index()+')').show();
    }
  });
});

However, it does not work as intended. The prices appear on the 1st and 3rd elements regardless of which second checkbox is clicked, and they do not switch back when the first checkbox is selected elsewhere. Any suggestions?

Answer №1

To increase the usability of your radio buttons, enclose each selection in a

<fieldset></fieldset>

By doing this, you can make them function independently and then utilize jQuery closest() to target the elements you want to hide.

Visit this link for more information on jQuery closest()

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

After refreshing the page, users are redirected back to the login page

On my website, I created a main page and an index.html page that redirects to the main page through a login panel. The issue I am encountering is that when I log in successfully on the main page and then refresh the page, it takes me back to the login pag ...

Looking for a way to focus on an element similar to `event.target.focus()`

I am in the process of developing a dynamic list component that generates an empty text field every time an item is added to the list. The structure of the component is shown below: const DynamicInputList = ({ inputs, onChangeArray, label, name, errors }) ...

Revamp the layout of the lower HTML video menu

Here is my code: <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> video { width: 100%; height: auto; } </style> </head> <body> <video width="400" controls> ...

What is causing these divs to shift apart instead of staying next to each other when the browser window is resized?

I am facing an issue with two of my divs not staying next to each other when resizing the browser window. They align perfectly when the window is wide, but as soon as I resize it to a narrower resolution, the right div moves below the left one: http://jsfi ...

The dropdown menu is being truncated

I am having an issue with a drop-down menu being cut off by its parent div. When I increase the height of the parent div, the drop-down menu becomes visible. Can someone please assist me? Below is my code snippet: MarkUp <div id="main-navigation" clas ...

Should CSS properties be applied directly to the html tag?

Surprisingly, I recently discovered that it's possible to set the background-color of the html tag. It seems strange since I always thought the body was responsible for containing the first rendered tag. I used to believe that the html tag was just a ...

Is it possible to achieve a FadeIn effect without using the .hide()

Is there a way to achieve a fadeIn effect without interfering with margins when the object is hidden from the document? I would like it to animate from opacity 0, but I am struggling to make it work. Any suggestions or ideas would be greatly appreciated. ...

Unexpected format of _id is returned by Mongolian DeadBeef .toArray() method

My love for Mongolian deadbeef is strong, but I'm facing a challenge. I want the output of a simple .find() method to match the JSON format from Mongo's command line: $ db.mycollection.find(); # outputs.. # { ...some data... , "_id" : ObjectId(" ...

Displaying items in the shopping cart across two separate columns

I have a website located at Within that page, I have included the Cart table using a woocommerce shortcode. Currently, the cart table is positioned below the billing details and payment options section. My goal is to move this cart table to be situated ...

"Resetting count feature in AngularJS: A step-by-step guide

I have a list consisting of four items, each with its own counter. Whenever we click on an item, the count increases. I am looking to reset the counter value back to zero for all items except the one that was clicked. You can view the demonstration here. ...

Next.js triggers the onClick event before routing to the href link

Scenario In my current setup with Next.js 13, I am utilizing Apollo Client to manage some client side variables. Objective I aim to trigger the onClick function before navigating to the href location. The Code I'm Using <Link href={`/sess ...

Variable width items inside an overflow-x container

I'm searching for a solution to create a vertical navigation list that can accommodate elements wider than the container itself. Since users have the freedom to input any names for the items, I cannot predict their width, except maybe by setting a ver ...

Struggling with a character entity in Javascript? Learn how to escape it and avoid any display issues (such as showing

document.title = ("welcome &rarr; farewell"); Trying to display the arrow symbol "→" but it's not showing correctly. Any tips on how to properly escape it? ...

Pug conditional elements not styling with CSS

Currently immersed in the world of Pug, node.js, and express as I build a web application. Facing hurdles when trying to style elements within Pug conditionals using CSS. For instance, consider this Pug snippet: div(id='outside') if authoris ...

Is it possible to use AJAX to change the class name of a Font Awesome icon?

I am considering updating the icon after deleting a row. Should I initially include the font awesome icon once in the blade, then remove the class name and add it back with ajax? blade: <div id="status-{{ $country->id }}"> <div id ...

React Context Matters: Troubles Unleashed

I've been facing some difficulties with passing a value from one file to another. The problem seems to be related to implementing context, but I can't seem to figure out where I went wrong! import React from 'react' const Mycontext = ...

What is the best way to import an external file from the project's root directory using webpack?

I am currently working on a unique npm package that will allow for the integration of custom rules from the project root. This functionality is similar to how prettier searches for a .prettierrc file in the project root. For this particular package, I am ...

Tips for displaying the date in 13-digit Unix Timestamp format using JSpreadSheet

I am faced with a challenge involving data that is stored in Unix Timestamp format, which I need to display as a readable date (e.g. YYYY/MM/DD) in JSpreadSheet ("jspreadsheet-ce"). Currently, the data appears as a 13-digit number and looks unattractive. ...

Maximizing values entered into form fields

Looking for a way to extract the highest number from a set of input fields in an HTML form using JavaScript? Take this example: <input id="temp_<strong>0</strong>__Amount" name="temp[<strong>0</strong>].Amount" type="text" valu ...

Firefox does not support CSS transitions

I've put in a lot of effort and even tried searching on Google, but I'm unable to find a solution to my problem: To help you understand my issue better, I have created a jsfiddle with my source code: Click here to view my Source Code Although e ...