Utilizing JavaScript to dynamically apply a CSS element when an input is selected as checked

Here is the code I am currently working with:

<div class="form-control-switch-option">
    <input type="radio" data-value="Buy">
    <label class="form-control-switch-option-label text-color__dark btns-family">For Sale</label>
</div>

<div class="form-control-switch-option">
    <input type="radio" data-value="Buy" checked="checked">
    <label class="form-control-switch-option-label text-color__dark btns-family">For Sale</label>
</div>

I would like to add the class "working" to the parent element (form-control-switch-option) when the input element is checked. So, in the example above, it should look like this:

<div class="form-control-switch-option">
    <input type="radio" data-value="Buy">
    <label class="form-control-switch-option-label text-color__dark btns-family">For Sale</label>
</div>

<div class="form-control-switch-option working">
    <input type="radio" data-value="Buy" checked="checked">
    <label class="form-control-switch-option-label text-color__dark btns-family">For Sale</label>
</div>

Is there a way to achieve this using only vanilla JavaScript (no jQuery)?

Answer №1

This script will apply the 'working' class immediately and upon interaction.

let radios = document.querySelectorAll('input[data-value="Buy"]')
for (let i = 0; i < radios.length; i ++) {
      // add 'working' class if checked automatically
      if (radios[i].checked) {
          radios[i].parentElement.classList.add('working')
      }
      // add 'working' class by clicking
      radios[i].addEventListener('change', function () {
          this.parentElement.classList.add('working')
      })
}

To make the checkbox functional, you need to use data-value="buy". If you prefer using a class, adjust the querySelectorAll accordingly, for example:

document.querySelectorAll('.input-class')

The process remains the same

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

"I encountered a CORS error with Framework7's $$.ajax, yet interestingly enough,

Struggling for hours with CORS error while using Framework $$.ajax, I finally decided to seek assistance from the community. I am experimenting with PhoneGap and Framework7. Trying to access an API on my .local domain is resulting in a CORS error "Cross-O ...

How can one properly transition an Angular 1 provider to Angular 2?

While there is ample documentation and examples available on how to convert Angular 1 services and factories to Angular 2, the process of converting an ng1 provider to its equivalent in ng2 seems to be a bit more scarce. Here's an example of a provid ...

Displaying multiple arrays using ng-repeat

My task is to display a list organized by date, but the problem is that the list is not sorted and I can't figure out when the date changes. This situation is similar to having the following Json: list = {name: first, date: 2014-05-21}, { {name: sec ...

Adjusting the height of a Jquery Fancybox to allow for scrolling down

I've implemented fancybox to display certain pages on my website, but I'm struggling with setting a fixed height and enabling scrolling for content that exceeds this height within the fancybox. Here are the parameters I have used: <script> ...

Tips for managing the number of items returned in a dataProvider using AS3

*Hey there! I'm looking to only display 100 items in a list component from a dataProvider, even if it contains more than 500 or even 1000 items. Specifically, I want the first 100 items with cameras on to be included, and then fill the rest to reach a ...

Managing numerous inquiries from a single customer within a succession of brief intervals

After creating a web application with a dashboard to showcase different reports and graphs based on user selections, I encountered an issue. Users can interact with the reports using checkboxes and radio buttons. Every time a checkbox or radio button is s ...

Applying the Directive/Isolated Scope as Embedded HTML within an Angular-Bootstrap Popover

If you're using the angular-ui popover, you have the ability to include HTML content within it. However, I encountered some difficulties in placing a directive called sampleDirective inside the popover. Despite my attempts with the $sce.trustAsHtml an ...

Utilizing v-model dynamically to showcase the outcomes of a specific property within a v-for iteration

As I iterate over an array using v-for, the number of items in this array varies each time. Currently, I am able to input values into the fields and have them correctly update the data property associated with them. However, there are two issues that need ...

Express.js Issue: Error in JSON Object Returned When Date Parameter is Empty

Currently tackling the challenges of the FreeCodeCamp Timestamp Microservice project and facing a roadblock in the implementation. While most requirements are met successfully, there's an issue with handling an empty date parameter test case. Let me b ...

Is it possible to position images in a circular layout around a central

I am struggling to position small planetary images around the main logo in a way that creates a satellite-like effect. Despite my efforts with positioning and margins, I have not been successful in achieving the desired look. Additionally, when I insert th ...

Nightwatch.js isn't registering the click event on MacBook when using Chrome browser

Being relatively new to nightwatch.js and test automation using javascript, I have encountered several problems which I managed to solve somehow. However, there is one issue that I am struggling to fix. The problem lies in the fact that nightwatch can loc ...

Using jQuery to easily transfer the direct image URL from an input field to a designated div element

In order to enhance the learning experience of 8th-grade chemistry students studying the periodic table of elements, I am working on a project that involves creating an "Augmented Reality" tool. The goal is to allow students to input a direct URL for an im ...

Tips for keeping a button selected in each row of a table

I'm confused about a simple issue. I have a table that fetches data from a JSON file, where each row represents a JSON field. In each row, I added two buttons (Like/Dislike) to assess the search quality. However, whenever I click on the like button on ...

Guide on sending a JavaScript function to a Pug file using Node.js and Express

In my recent project, I developed a node app using express along with a pug file. The express app is configured to listen on port 3000 and render the pug file. One of the key functionalities involves fetching information from an external API. My goal is to ...

Using the `explode()` function, learn how to accurately count only the initial paragraphs

I'm facing an issue with Paragraphs inside Blockquotes, and I need a solution to exclude those paragraphs from my count. Essentially, I want to ignore blockquote elements. $banerAfter[2] = "<div>nineth</div>"; //display after the second p ...

The generation of noisy URLs with hidden inputs is caused by the checkboxes in Thymeleaf Spring forms

Thymeleaf Spring automatically generates hidden inputs for checkboxes in forms, as explained in the documentation at When submitting the form using a GET method, the resulting URL can be quite lengthy and noisy: /search?q=stuff&_filters=on&filter ...

Which is more effective for transferring data between pages: HTML5 storage or Angular services?

I'm currently exploring ways to transfer data between two pages that have Angular controllers. So far, I've discovered two methods for passing data: through an Angular service (similar to the example found here) using HTML5 storage opti ...

Execution of a route within another route in Node.js is facing a setback and not being processed as expected

Hey there, I am currently working on a function that includes a route calling the Auth0 API with updated data from the client. The function is running fine, but for some reason, the app.patch() method isn't executing as expected. I'm a bit stuck ...

Transform Promise-based code to use async/await

I'm attempting to rephrase this code using the async \ await syntax: public loadData(id: string): void { this.loadDataAsync() .then((data: any): void => { // Perform actions with data }) .catch((ex): v ...

Show live data in JQgrid on Codeigniter platform

I'm currently working on a project using CodeIgniter that involves implementing a JQgrid table to display data. While I am able to retrieve the data from the database, I have encountered difficulties in displaying it within the JQgrid itself. However, ...