How can we add a class to a radio button using jQuery when it is checked, and remove the class when it

I'm looking for help with using jQuery to toggle between two radio buttons and display different divs based on the selection.

jQuery(document).ready(function($) {

  if ($('#user_personal').is(':checked')) {
    $('.user_company').addClass('hidden');
    $('.user_personal').removeClass('hidden');
  } else if ($('#user_company').is(':checked')) {
    $('.user_personal').addClass('hidden');
    $('.user_company').removeClass('hidden');
  }

});
.hidden {
  display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="user-type-item">
  <input name="user" id="user_personal" type="radio">
</div>
<div class="user-type-item">
  <input name="user" id="user_company" type="radio">
</div>

<div class="user_personal">
  <select name="" id="" class="form-control">
    <option value="0"></option>
  </select>
</div>

<div class="user_company">
  <input type="text" class="form-control">
</div>

This jQuery code will show/hide div elements based on which radio button is selected. When "#user_personal" is checked, "div.user_company" will have the "hidden" class added and "div.user_personal" will have it removed. Similarly, when "#user_company" is checked, "div.user_personal" will have the "hidden" class added and "div.user_company" will have it removed.

Thank you in advance for any assistance!

Answer №1

Utilize the toggleClass function to switch between displaying the select and input elements.

$('.user-type-item input').click(function(){
     $('.user_personal,.user_company').toggleClass('hidden');

});
.hidden {
  display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="user-type-item">
  <input name="user" id="user_personal" type="radio" checked>
</div>
<div class="user-type-item">
  <input name="user" id="user_company" type="radio">
</div>

<div class="user_personal hidden">
  <select name="" id="" class="form-control">
                     <option value="0">Select an option.</option>
               </select>
</div>

<div class="user_company">
  <input type="text" class="form-control">
</div>

multiple elements:

$('.user-type-item input').click(function() {
  var ind = $(this).parent().index();
  $('.el').addClass('hidden');//hide all inputs
  $('.el').eq(ind).toggleClass('hidden');//show only the input corresponding to the checked radio

});
.hidden {
  display: none
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="user-type-item">
  <input name="user" id="user_personal" type="radio" checked>
</div>
<div class="user-type-item">
  <input name="user" id="user_company" type="radio">
</div>
<div class="user-type-item">
  <input name="user" id="user_company" type="radio">
</div>
</div>
<div class="el user_personal">
  <select name="" id="" class="form-control">
                     <option value="0">Select an option.</option>
               </select>
</div>

<div class="el user_company hidden">
  <input type="text" class="form-control">
</div>
<div class="el user_company hidden">
  <input type="text" class="form-control" value="2">
</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

What causes the $_FILES superglobal to consistently appear empty?

Check out my page Take a look at my form: <h2>Upload Photo</h2> <form name="photo" enctype="multipart/form-data" action="<?php echo $_SERVER["PHP_SELF"];?>" method="post"> Photo <input type="file" name="image" size="30" /> & ...

Dispatching $emit / $broadcast events from multiple areas of the code and capturing them in a single location

I have a practice of sending $emits (or $broadcasts) from various parts of the code and different controllers, but intercepting them all from one centralized place. While this approach seems to be functioning properly, I am unsure if it may be considered b ...

Unexpected Behavior Arises from Axios Get API Request

Below is a functional example in my CodePen showing what should be happening. Everything is working as intended with hard coded data. CodePen: https://codepen.io/anon/pen/XxNORW?editors=0001 Hard coded data: info:[ { "id": 1, "title": "Title one ...

Ensure that the child div is anchored to the bottom of the parent div container

I am looking for a way to ensure that the subfooter div stays at the bottom of the childbox div, similar to a footer. You can view the code on this jsfiddle link <div class="parentbox"> <div class="childbox"> <div id="subfooter" ...

Tips for updating the color of buttons after they have been selected, along with a question regarding input

I need help with a code that changes the color of selected buttons on each line. Each line should have only one selected button, and I also want to add an input button using AngularJS ng-click. I am using AngularJS for summarizing the buttons at the end ...

Axios is passing an array instead of a JSON object when making a POST request

I am trying to make a post request using axios in my Vue.js front-end to communicate with Laravel on the backend. const data = { file: {id} } axios.post('api/documents/remove', data).then((response) => { ...

The sequence of execution in React hooks with Typescript

I'm having difficulty implementing a language switching feature. On the home page of my app located at /, it should retrieve a previously set preference from localStorage called 'preferredLanguage'. If no preference is found, it should defau ...

Maintain saved states upon page load/refresh using jQuery Cookies

I'm currently working on enhancing the accessibility features of a website. To achieve this, I have integrated three toggle buttons - one for adjusting font size, another one for highlighting links, and the third one for inverting colors. My objective ...

What are the steps to implement localStorage in Vuejs3?

I'm feeling a bit lost when it comes to localStorage and its usage. I have a component called Statistic.vue which displays a modal at the end. Statistic.vue <template> <p class='modal'>{{numberOfGames}}</p> </template& ...

Unable to insert text into JEditorPane using text/html format

In my class, I am using a JEditorPane to display text that needs to support HTML. When I try to add text to the pane by setting the content type to HTML and then using setText(), nothing appears on the pane. The issue seems to be with setting the content ...

Making a POST request to a REST service in Rails 3 using Phonegap

I've encountered an issue with my rails3 rest service while developing a phonegap app using HTML5 and jQuery javascript. Specifically, I'm struggling to make a POST rest call with ajax jQuery due to cross domain security restrictions. Does anyon ...

Unlocking the potential of the :not selector when combined with the :nth-of-type selector

My current project involves styling a table. I am looking to apply a specific background color to each odd row, excluding the first row which contains headers. I attempted the following code without success: .new-items-table tr:nth-of-type(odd):not(.new- ...

Having trouble with AES decryption on my nodeJS/ExpressJS server backend

Looking to decipher data post retrieval from mongoDb. The retrieved data comprises encrypted and unencrypted sections. app.get("/receive", async (req, res) => { try { const data = await UploadData.find(); const decryptedData = data. ...

What is the reason behind watches not triggering when there are changes in history?

<script setup> import InputChat from '../components/InputChat.vue' import Chat from '../components/Chat.vue' import Layout from "@/components/Layout.vue"; import Sidebar from "@/components/Sidebar.vue"; import ...

expanding the close window icon beyond the boundaries of the modal container

I seem to be experiencing a CSS mistake that I can't figure out. The close window icon in my modal window is getting cut off at the edge and not displaying properly. Check out this JSFiddle link <div id="sendMsgForm" class="modal"> <div ...

Design a circular progress bar with a cut-off at the bottom

Does anyone have suggestions on how to create a circular progress bar with cropping at the bottom, similar to this example: PROGRESS BAR? I've been searching for a component like this but haven't had any luck. Any ideas, especially utilizing Mate ...

A pale tooltip with a light arrow appearing against a soft white backdrop

Can someone help me figure out how to display a white tooltip with a white arrow? I've tried to implement it using the code below, but the white color is not visible against the background. Any suggestions on making it stand out? $(function () { ...

Tips for verifying a login modal on an asp.net webforms using jQuery?

I am currently working on an asp.net webpage that utilizes a modal bootstrap for user login. Upon clicking the Login button, it should authenticate the user and initiate a server-side method called "ExportToZip" to download a zip file. My issue lies in ens ...

Extracting web search result URLs using Puppeteer

I'm currently facing an issue with the code I've written for web scraping Google. Despite passing in a specific request, it is not returning the list of links as expected. I am unsure about what might be causing this problem. Could someone kindly ...

Sharing jquery variables between an iframe and its parent window

How can I manipulate data between jQuery and iframes? Specifically, how do I retrieve and pass variables from an iframe to the body, and vice versa? Consider the example below. How can I trigger a button click event within an iframe that affects the conten ...