Modifying the appearance of radio buttons using jQuery

I'm new to jQuery and I'm finding it challenging. Currently, I have a set of three radio buttons with the third button already prechecked. My aim is to change the CSS class of the checked button, making it similar to an unchecked button with the class "btn-outline-success", and if it's checked, adding the class "btn-success". To achieve this, I am using Bootstrap styling.

Is there a way to visually indicate that a radio button is checked by showing a hover effect?

I attempted the following approach, but I am dissatisfied with the hardcoded nature of it. Moreover, it doesn't work as intended and would require numerous if statements.

Additionally, when I click on another radio button, only the next one gets modified while the previous one retains its "checked" classes.

Is there a solution that works like this in plain words: "If a radio button is checked, show this with the hover effect from the specified CSS classes"?

$("label").click(function() {
  if ($("#customRadioInline1").is(":checked")) {
    $("#radio1").removeClass("btn-outline-success");
    $("#radio1").addClass("btn-success");
  }
  if ($("#customRadioInline2").is(":checked")) {
    $("#radio2").removeClass("btn-outline-secondary");
    $("#radio2").addClass("btn-secondary");
  }
  if ($("#customRadioInline3").is(":checked")) {
    $("#radio3").removeClass("btn-outline-info");
    $("#radio3").addClass("btn-info");
  }
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

<div class="custom-control-inline">
  <label class="btn btn-outline-success" id="radio1" for="customRadioInline1">
        <input type="radio" id="customRadioInline1" name="status" value="Seriös" class="custom-control-input" />
        BUTTON1
    </label>
</div>
<div class="custom-control-inline">
  <label class="btn btn-outline-secondary" id="radio2" for="customRadioInline2">
        <input type="radio" id="customRadioInline2" name="status" value="Hotline" class="custom-control-input" />
        BUTTON2</label>
</div>
<div class="custom-control-inline">
  <label class="btn btn-outline-info" id="radio3" for="customRadioInline3">
        <input type="radio" id="customRadioInline3" name="status" value="Neutral" checked="checked"
            class="custom-control-input" />
        BUTTON3</label>
</div>

<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>

Answer №1

In order to update the functions that you have written, it is necessary to make some changes:

$("#radio2") - Make note that this will retrieve an html element and addClass function cannot be used directly on an html element.

It's suggested to use the following instead:

$("#radio2").classList.remove('btn-outline-success')
$("#radio2").classList.add('btn-success')

You can give this a try and see if it works for your needs.

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

Error in Passport JS: Trying to use an undefined function

I've been struggling with debugging my code in Express and Passport. I've tried following solutions from others but can't seem to get it right. Any help or useful links would be greatly appreciated. Here is the error message along with the ...

How do I store the result of an Ajax request as a variable in a different function within a React component?

One of the challenges I'm facing involves making an ajax call that retrieves a list of movies, and then running another function with a separate ajax call to fetch the genre names. Since the first call only provides the genre IDs, I need to match each ...

The server's file URLs are modified within the page source of a WordPress site

I've been attempting to integrate Adsense code into a WordPress blog at demonuts.com. I placed the Google code in the TEXT WIDGET provided by WordPress. However, upon running the website, I noticed that the URLs for .js, .css, or .png files are being ...

Increasing the top padding of a resized iframe thanks to iframe-resizer

Currently, I am utilizing the remarkable iframe-resizer library to resize an iFrame while keeping it in focus. The challenge I am facing is my inability to figure out how to include additional padding at the top of the iFrame once it's resized. The ...

I am currently dealing with an issue where 3 controllers are responsible for fetching data from a database and displaying it in a dropdown list. However, the problem arises when a value is selected from the list as it

This particular one serves as the main controller and module for this page. var bookinsert = angular.module('bookinsert', ['ngCookies']); bookinsert.controller('book_insert_ctrl', function ($scope, $http, $rootScope, $cookies ...

Ways to ensure text fits nicely within a container: HTML & CSS

Below is a code snippet: @import url('https://fonts.googleapis.com/css?family=Merriweather|Open+Sans'); .square { max-width: 460px; background: white; border-radius: 4px; box-shadow: 0px 5px 20px #D9DBDF; -webkit-transition: all 0. ...

tips for making a row stand out in a massive table with jquery

When changes are made to data rows on tables or any other item with multiple rows of data, I have observed that the edited row temporarily turns yellow before returning to its original state. In my case, I have a data table with approximately 500 rows. A ...

Is it possible to bind a function to data in Vue js?

Can a function be data bound in Vue? In my template, I am trying something like this: <title> {{nameofFunction()}}</title> However, when I run it, it simply displays 'native function' on the page. Any insights would be appreciated ...

Why isn't my Enum functioning properly to display the colored background?

Why isn't the Background Color showing up when I pass in the BGColor Prop dynamically in my next.js + Tailwind app? I have tried passing in the prop for my component, but the color is not appearing. <Title title='This is HOME' descripti ...

I am having trouble grasping certain syntax in JavaScript when it comes to using `${method_name}`

I'm having trouble understanding some of the syntax in this code, particularly ${method_name}. I'm not sure what we are achieving by passing the method name within curly braces. global._jsname.prototype.createEELayer = function (ftRule) { if ...

The functionality of Material UI tooltip is not functioning properly when accessed on mobile devices

Attempting to transform Tooltip into a controlled component that relies on the onClick event. While this setup works well on mobile and web, it loses its original functionality of showing the Tooltip on hover. Is there a way to make the Tooltip function ...

Toggle the state of a Material UI checkbox in ReactJS based on the data from hooks that return a true or checked value

I need assistance with checking/unchecking a checkbox value in an edit modal based on the return of addAdvisory(hooks) which is 'Y', indicating true/checked. Below is my basic code snippet: const [addAdvisory, setaddAdvisory] = useState({ SY ...

Refreshing a React form

this.state = { name: "", arr: [], story: "" }; add(e) { e.preventDefault(); this.setState({ story: e.target.value }); this.state.arr.push(this.state.story); this.form.reset(); } <form action=""> <input onChange={this.b} type="t ...

Create an HTML table to view JSON data from a cell on a map

Looking to transform the JSON data into a table by organizing the information based on supplier and product. Below is the JSON input and code snippet: $(document).ready(function () { var json = [{ "Supplier": "Supplier1", "Product": "O ...

Utilize the Bootstrap column push-pull feature on the mobile version of

https://i.stack.imgur.com/yTBIt.png When viewing the desktop version, div A is displayed at the top of the page. However, I would like to move it to the bottom when viewing on a mobile device (col-xs). I have attempted to solve this issue myself without s ...

I need assistance setting up a Facebook page feed using Angular.js. I want to display the posts in a list of cards and include a fullscreen image gallery. Is

Hey there! I'm in the process of developing an app that pulls Facebook page posts and showcases them with custom CSS. The app is functioning smoothly with two controllers, DashCtrl and MainCtrl, each working fine on its own. However, when trying to tr ...

Step-by-step guide for serving static JavaScript files using NextJS

I am currently exploring the process of hosting static js and css files using NextJS. My journey began with creating a react app through create-react-app, where I developed an App component before executing the npm run build command. This resulted in the ...

Trouble with parsing JSON data in JQuery getJson callback

Recently, I've encountered a strange issue with using jQuery for JSON. Even though the server is responding correctly to the request, I'm having trouble extracting the data from the JSON response. The server is ASP.MVC and is serializing using J ...

Locating the top 3 largest values in an HTML data table and highlighting them in red

Issue Description: I am working with data that displays the electricity consumption of different buildings in HTML tables. There is a possibility that these tables may contain duplicate values. With the use of jQuery, I am seeking a method to identify an ...

Steer clear of duplicating patterns in vue templates

I have a significant issue with a component that needs to be repeated multiple times in the parent template due to the usage of v-if. The component code is as follows: <SelectCard v-for="(channel, index) in category.visibleChannels" :key="index + & ...