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

Attempting to enlarge logo or image when cursor hovers over it

Seeking to enhance logo/image size when cursor hovers over it, but facing an issue where it enlarges even on areas outside of the image itself - View Example. I followed a tutorial to achieve this effect, and specified the width as 1024x1024 for the logo/i ...

Is it possible to eliminate process.env.NODE_ENV using browserify/envify?

Currently, I am utilizing ReactJS through NPM and Browserify, but I am encountering difficulties while attempting to build it in production mode as mentioned in the readme. The code I have for setting up browserify is: var browserify = require('brows ...

Issue with vertical alignment in form input text area not functioning properly

Need some help aligning inputted text with the top of a textarea on an HTML form. I've scoured forums for solutions, but no luck so far. I attempted using: textarea{ vertical-align:top;} and input["textarea"]{ vertical-align:top;} Tried adding ...

Ways to separate my json object into multiple variables

I am looking to extract the following data: name, meetup, tag from my object and store them in separate variables or objects. Here is my json object: var data = { "MY_ID": 1, "module": [ { "name": "Manch ...

Executing a search within the current connection in Node.js

In the code snippet provided, the need is to execute the second SQL query (query2) after constructing it based on the results of the first query (query1). However, even though the second query is successfully built, it is not being executed. Assistance i ...

Exploring the connection between Jquery and Javascript event handling within ASP.NET C# code-behind, utilizing resources such as books and

It seems that Jquery, Javascript, and AJAX are gaining popularity now. I am interested in learning how to use this functionality within C#. Do you have any recommendations for resources or books that teach JavaScript from a C# perspective on the web? Not ...

Having difficulty in closing Sticky Notes with JavaScript

Sticky Notes My fiddle code showcases a functionality where clicking on a comment will make a sticky note appear. However, there seems to be an issue with the Close Button click event not being fired when clicked on the right-hand side of the note. I have ...

HeaderView in Angular Framework

When exploring the best practices for organizing an AngularJS structure, I came across the recommendation to implement partial views as directives. Following this advice, I created a directive for my app header. In my specific header design, I included a ...

Tips for retrieving the HTML file of a modified canvas in HTML5

I’m currently working on a project to develop a website that allows users to design their own pages by simply dragging and dropping elements onto the canvas. The goal is for users to be able to save their creations as an HTML file. I’m facing challen ...

Converting JSON data into an array of JavaScript objects

Here is some of the JSON data I have: [ { "items": [ { "retailername": "Zop Now", "value": 475 }, { "retailername": "Snap Deal", "value": 265 ...

Changes in query parameters on NextJS navigation within the same page do not activate hooks

When utilizing NextJS without SSR, I encountered an issue with basic navigation using different query parameters. Upon the initial arrival on the page/component, everything seems fine as the component gets mounted and URL params change accordingly. However ...

Problem with structuring a Html5 web page

Recently, I created a web page using HTML5. Check out the code below: <header> <img src="img/logo.png" alt="logo"> <hr class="hr-style"> <h1>The Articles</h1> <nav> <ul> <li><a href="#" ...

What is the best way to leverage local storage/memory to save information for my text-based RPG game?

Currently, I am in the process of creating a text-based RPG on Codecademy. However, I am facing a challenge when it comes to implementing a save/load system using JavaScript/HTML. My idea is to create a system where players can type "save" into a prompt, ...

Sending messages to all sockets in socket.io except the one who sent it

I'm currently working on integrating a chat feature into my app using socket.io. The process involves sending an API request to the server each time a user sends a message, which is then stored in the database. Only after this data storage step is com ...

An internal server error has occurred within the asp.net framework, resulting in

Seeking Solution: Currently, I am in the process of developing an application where I have implemented an HTML select list to choose a category. Using AJAX web method, I am trying to retrieve items and their respective images based on the selected category ...

Gather input from a form and store it in an Object upon submission

I am facing a challenge as I do not have much experience with object-oriented JavaScript. My goal is to have a form submit details such as the first and last name to an object that I've created. Here is the object I have: function Person(firstName, ...

Crafting a robust and secure password using Yup and Formik while receiving personalized error notifications

My Password Validation Dilemma I'm in the process of developing a password field that can assess the strength of the input provided. In a different response, I came across a regex that I could utilize to validate whether the input meets specific crit ...

Using jQuery, upon the page loading, the script will automatically trigger a

I am attempting to create an HTML file that automatically logs into my bank account. Below is the code I currently have: <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"> ...

Converting a text file to JSON in TypeScript

I am currently working with a file that looks like this: id,code,name 1,PRT,Print 2,RFSH,Refresh 3,DEL,Delete My task is to reformat the file as shown below: [ {"id":1,"code":"PRT","name":"Print"}, {" ...

most efficient method to execute numerous API requests at the same time

Currently, I am developing a backend using expressJS. Imagine that I need to make 10,000 calls to an API consecutively and store the obtained data in a database. What would be the most effective approach for achieving this task? Is it possible that Promis ...