Utilizing jQuery to style and remove styles from a clicked radio button by leveraging parent() and next() methods

In my project, I have 3 identical sections that are exactly the same as each other. What I want to achieve is a functionality where when I click on the ".rad1" (first radio button), its label gets styled. Similarly, when I click on ".rad2", it should remove the style from the first radio button and apply it to the second radio button. Importantly, this styling change should only occur within the section being clicked, not affecting any other section.

Although I have attempted the following code snippet, I haven't been successful in achieving the desired outcome:


$('.rad1').click(function() {
    $(this).parent('.label1').css('background', 'red');
});
$('.rad2').click(function() {
    $(this).parent().next('.label1').css('background', 'transparent');
    $(this).parent('.label2').css('background', 'red');
});


.form-section {
    background: orange;
    border: 1px solid black;
}


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-section">
    <form action="">
        <div class="first">
            <label for="radio" class="label1">
                <input type="radio" class="rad1" name="rad">First
            </label>
        </div>
        <div class="second">
            <label for="radio" class="label2">
                <input type="radio" class="rad2" name="rad">Second
            </label>
        </div>
    </form>
</div>
<!------------SECTION-->
... (repeat similar structure for the remaining sections)

Answer №1

This example demonstrates how to achieve the desired effect:

$('input[name="rad"]').click(function() {
  $(this).closest('form').find('label').removeClass('selected'); // Remove 'selected' class from all labels
  $(this).parent().addClass('selected'); // Add 'selected' class to the parent of the clicked input
});

$('input[name="rad"]').click(function() {
  $(this).closest('form').find('label').removeClass('selected');
  $(this).parent().addClass('selected');
});
.form-section {
  background: orange;
  border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-section">
  <form action="">
    <div class="first">
      <label for="radio" class="label1">
        <input type="radio" class="rad1" name="rad">First
      </label>
    </div>
    <div class="second">
      <label for="radio" class="label2">
        <input type="radio" class="rad2" name="rad">Second
      </label>
    </div>

  </form>
</div>
<!------------SECTION-->
<div class="form-section">
  <form action="">
    <div class="first">
      <label for="radio" class="label1">
        <input type="radio" class="rad1" name="rad">First
      </label>
    </div>
    <div class="second">
      <label for="radio" class="label2">
        <input type="radio" class="rad2" name="rad">Second
      </label>
    </div>

  </form>
</div>
<!------------SECTION-->
<div class="form-section">
  <form action="">
    <div class="first">
      <label for="radio" class="label1">
        <input type="radio" class="rad1" name="rad">First
      </label>
    </div>
    <div class="second">
      <label for="radio" class="label2">
        <input type="radio" class="rad2" name="rad">Second
      </label>
    </div>

  </form>
</div>

It's recommended to use classes for styling instead of directly applying CSS with .css().

Answer №2

$('.option1').click(function(){ 
   $(this).parent()
     .css('background','blue');
});
$('.option2').click(function(){
   $(this).closest('div')
     .prev().find('.title')
     .css('background','transparent');
   $(this).parent()
     .css('background','blue');
});

Answer №3

Your strategy is one of many that can be used, but I prefer to stick with the following approach:

$('.rad1').click( function() {
    $(this).parent('.label1').css('background', 'red');
    $('.rad2').parent('.label2').css('background', 'transparent');
});
$('.rad2').click( function() {
    $(this).parent('.label2').css('background', 'red');
    $('.rad1').parent('.label1').css('background', 'transparent');
});

Answer №4

You can achieve the same result using only CSS without the need for JavaScript, by making a simple adjustment to the structure.

To do this, start by following j08691's code snippet, comment out the JavaScript section, and rearrange the label so it follows the <input> element instead of enclosing it.

After restructuring the elements, you can create a CSS selector that targets the label as a sibling of a checked radio button. Unchecked buttons will maintain their original orange background.

/*$('input[name="rad"]').click(function() {
  $(this).closest('form').find('label').css('background', 'transparent')
  $(this).parent().css('background', 'red');
});*/
.form-section {
  background: orange;
  border: 1px solid black;
}
.form-section input[type="radio"]:checked + label {
    background: red;
}
<div class="form-section">
  <form action="">
    <div class="first">
        <input type="radio" class="rad1" name="rad">
        <label for="radio" class="label1">First</label>
    </div>
    <div class="second">
        <input type="radio" class="rad2" name="rad">
        <label for="radio" class="label2">Second</label>
    </div>

  </form>
</div>
<!------------SECTION-->
<div class="form-section">
  <form action="">
    <div class="first">
        <input type="radio" class="rad1" name="rad">
        <label for="radio" class="label1">First</label>
    </div>
    <div class="second">
        <input type="radio" class="rad2" name="rad">
        <label for="radio" class="label2">Second</label>
    </div>

  </form>
</div>
<!------------SECTION-->
<div class="form-section">
  <form action="">
    <div class="first">
        <input type="radio" class="rad1" name="rad">
        <label for="radio" class="label1">First</label>
    </div>
    <div class="second">
        <input type="radio" class="rad2" name="rad">
        <label for="radio" class="label2">Second</label>
    </div>

  </form>
</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

Is there a way to insert a dot after every two digits in a text field using Javascript upon keypress?

When inputting a 4-digit number (e.g. 1234) in my text field with value format 00.00, I want it to automatically adjust to the 12.34 format. How can I achieve this behavior using JavaScript on keyup event? ...

Filtering data in AngularJS by parsing JSON records

I have a JSON file containing restaurant information and I need to display the data by grouping them based on their respective address fields. For example, all restaurants with the address 'Delhi' should be shown first, followed by those from &ap ...

Tips for Formatting Mandatory Message Input Fields and Text Boxes

I am in the process of creating a contact page for my Reactjs website, but I am unsure how to style the required message that should appear below the input or textarea upon clicking Submit. Can anyone guide me on how to achieve this? Relevant Code <for ...

Angular displaying a slice of the data array

After following the example mentioned here, and successfully receiving API data, I am facing an issue where only one field from the data array is displayed in the TypeScript component's HTML element. Below is the content of todo.component.ts file im ...

What are some simple methods for designing a bootstrap layout?

I am in the process of developing a single page application and I need to design customized screens. I have experimented with various online tools for creating bootstrap layouts. Are there any free software options available that can help with screen lay ...

Changing a JSON reply to an object using JQuery within Symfony2

I recently delved into the world of AJAX and Json, working on creating a call for a thread of comments to be displayed on my webpage. After the controller finishes loading, it returns an array of objects in Json format: '[{"usr":"gigi","usrpic":"4993 ...

How can we ensure all elements in a row are aligned at the top?

My goal is to position the elements in a row, which is enclosed within a container, at the top of that row. Here is the current structure of my HTML: <div class="container"> <div class="row"> <div class="ticket"> ...

Uploading an image along with additional information to Strapi using React

Can you assist me with allowing users to post data on Strapi, such as their name, URL, description, and image? I attempted to add an input type file but encountered a 500 error. I suspect this could be due to the need to call localhost:1337/upload, but I& ...

During the animation sequence, the element is seen ascending

I'm encountering a small issue with one of the elements I'm animating - it's moving up slightly during the animation process. It elevates about 2-3 pixels while the animation is playing, then snaps back down once it's completed. The el ...

The issue with ThreeJS where the camera movement stops working after clicking

Seeking assistance with implementing camera movement in ThreeJS. Despite having no errors, clicking the button does not trigger the camera movement as expected. The function aimed at moving the camera by 200 units in all directions seems to have no effec ...

Issue with passing props from parent component to child component in Vue.js not functioning

As a newcomer, I have been assigned a project that involves using Vuejs. In this project, there is a page that utilizes a component called DashboardCard. Each DashboardCard receives 2 props - val and icon from the parent component. https://i.stack.imgur. ...

Creating a sleek animated analog clock using CSS and jQuery

I am facing a small issue with my CSS3/jQuery analog clock. Currently, the movement of the clock hands is a bit abrupt. I would like the animation to be smooth. I attempted using transition: all .1s, but it gets messy when the clock hands reach the top po ...

Tips for displaying my libraries' function arguments while hovering in VSCode

As the creator of a JavaScript library, I am intrigued by how some libraries display function parameters and definitions when hovering over them in VSCode. Despite my efforts to add jsdoc style comments around the class definitions, I have not been able to ...

Is there a way to retrieve the href value from a modal window upon clicking the link?

When clicking on the a href, I am attempting to retrieve a value in my pop-up window. I am using magnificPopup JavaScript Below is the code for my a href tag and I want to fetch the "data-stream" value in the pop-up window. <a class="popup-with-zoom ...

The routing feature functions properly on localhost but encounters issues on the live server

There seems to be an issue with this code. While it works perfectly on localhost, it doesn't function as expected on a live Apache server. I have already specified the homepage in the package JSON file and included an htaccess file. However, when acce ...

Using jQuery to dynamically insert an HTML element into a table

I'm trying to insert a hyperlink into an empty HTML table. This function works perfectly fine on Firefox and Chrome, taking only 0.2 seconds to load. However, when I try it on IE9, it takes at least 3 minutes to display the link. The issue seems to be ...

How does the HTML file in the build directory connect to the JavaScript file in the source directory when setting up a create-react-app

After initializing our react app by running the command create-react-app, a new app directory is created with sub-directories included. When we use the command npm start to run the app, it deploys the index.html file located in the public directory withi ...

Issue: Query cannot be added to the queue after quit has been called

I am encountering an error "Error: Cannot enqueue Query after invoking quit" when trying to run the code below. I need assistance with inserting data into two tables. As a newcomer to node.js, I would greatly appreciate your help in correcting the code. ...

Media queries in CSS appear to be dysfunctional when used on Microsoft Edge

@media (min-width: 992px) and (max-width: 1140px) { .mr-1024-none { margin-right: 0px !important; } .mt-1024 { margin-top: 1rem !important; } .d-1024-none { display: none !important; } } Utilizing the ...

I'm currently in the process of creating a snake game using HTML5. Can you help me identify any issues or problems that

I am experiencing an issue where nothing is appearing on the screen. Below are the contents of my index.html file: <html> <body> <canvas id="canvas" width="480" height="480" style="background-color:grey;"></canvas> <script src=" ...