Div behaving as a radio input

I have customized radio buttons to look like buttons using JavaScript. However, on page load, both buttons automatically receive the 'active' class instead of only when they are selected. Additionally, the fadeToggle function in the if-statement is behaving as though the buttons are checkboxes, requiring two clicks to deactivate. I suspect these issues are related.

Does anyone have any suggestions on how to fix this?

var rsvpAns = $('.radioTransform');
rsvpAns.click(function() {
  $('.radio', this).prop('checked', !$('.radio', this).prop('checked')).change();
  var radioCheck = $('.radio', this).val();
  $('.radioTransform', this).toggleClass('active');
  console.log(radioCheck);
  if (radioCheck == 'Yes') {
    $('#ansYes').fadeToggle(400);
  }
});
.radio {
  display: none;
}

#pushR {
  margin-right: 25px;
}

.radioTransform {
  width: 220px;
  display: inline-block;
  vertical-align: top;
  background: #dbc8ca;
  cursor: pointer;
  padding: 15px 0;
}

.radioTransform.active {
  background: red;
}

.radioAnswer {
  font-family: 'Open Sans', sans-serif;
  font-size: .9rem;
  text-align: center;
}

#ansYes {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="rsvpForm">
  <div class="formField">
    <div class="radioTransform" id="pushR">
      <span class="radioAnswer">YES</span>
      <input type="radio" value="Yes" class="radio">
    </div>
    <div class="radioTransform">
      <span class="radioAnswer">NO</span>
      <input type="radio" value="No" class="radio">
    </div>
  </div>
  <div class="formField" id="ansYes">
    <label class="label">How are you doing?</label>
    <input type="text" class="input">
  </div>
  <input type="submit" value="Submit RSVP" id="submit">
</form>

Answer №1

If you want to avoid using Javascript completely, you can achieve the same functionality with clever CSS and a simple reorganization of your HTML structure. This approach not only enhances the semantic meaning but also improves accessibility.

To demonstrate how it works, I have included some Javascript solely for console logging purposes.

Keep in mind that for radio buttons to function correctly, they must share the same name attribute; otherwise, both buttons can be selected simultaneously.

const radios = Array.from(document.querySelectorAll('[name="yesno"]'))

for (const radio of radios) {
  radio.addEventListener('change', function() {
    value.textContent = document.querySelector('[name="yesno"]:checked').value
  })
}
.radio {
  display: none;
}

.radioAnswer {
  width: 220px;
  display: inline-block;
  vertical-align: top;
  background: #dbc8ca;
  cursor: pointer;
  padding: 15px 0;
  transition-duration: .4s;
  position: relative;
}

.radioAnswer::before {
  display: inline-block;
  content: "";
  border-width: 0 2px 2px 0;
  border-color: transparent;
  border-style: solid;
  width: 0;
  height: 0;
  transition: width .4s linear .1s, 
    height .2s linear 1.6s;
  position: absolute;
  left: 10px;
  top: 50%;
  transform: rotate(35deg) translateY(-50%);
  transform-origin: center right;
}

input[type=radio]:checked+.radioAnswer {
  background: #0a0;
  color: #fff;
}

input[type=radio]:checked+.radioAnswer::before {
  border-color: #fff;
  transform: rotate(35deg) translateY(-50%);
  height: 1.5em;
  width: .8em;
  transition: all .4s linear 0s, width .4s linear .1s, height .2s linear .3s;  
  position: absolute;
}

.radioAnswer {
  font-family: 'Open Sans', sans-serif;
  font-size: .9rem;
  text-align: center;
}
<input type="radio" value="Yes" class="radio" name="yesno" id="yes">
<label class="radioAnswer" for="yes">Yes</label>
<input type="radio" value="No" class="radio" name="yesno" id="no">
<label class="radioAnswer" for="no">NO</label>
<p>Selected Value: <strong id="value"></strong></p>

Answer №2

When you only trigger the yes button in your if condition block, what happens if you select no? In that case, it would be helpful to include an else statement as well. Additionally, the code snippet shows that the 'radioTransform' div does not initially have the active class upon loading.

var rsvpAns = $('.radioTransform');
rsvpAns.click(function() {
  $('.radio', this).prop('checked', !$('.radio', this).prop('checked')).change();
  var radioCheck = $('.radio', this).val();
  console.log(radioCheck);
  
  $(this).toggleClass('active');
  if (radioCheck == 'Yes') {
    $('#ansYes').fadeToggle(400);
   if($(this).next('.radioTransform').hasClass('active')){
    $(this).next('.radioTransform').removeClass('active');
   }
  } else {
    $('#ansYes').fadeOut(400);
  if($(this).prev('.radioTransform').hasClass('active')){
   $(this).prev('.radioTransform').removeClass('active');
   }
  }
});
.radio {
  display: none;
}

#pushR {
  margin-right: 25px;
}

.radioTransform {
  width: 220px;
  display: inline-block;
  vertical-align: top;
  background: #dbc8ca;
  cursor: pointer;
  padding: 15px 0;
}

.radioTransform.active {
  background: red;
}

.radioAnswer {
  font-family: 'Open Sans', sans-serif;
  font-size: .9rem;
  text-align: center;
}

#ansYes {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="rsvpForm">
  <div class="formField">
    <div class="radioTransform" id="pushR">
      <span class="radioAnswer">YES</span>
      <input type="radio" value="Yes" class="radio">
    </div>
    <div class="radioTransform">
      <span class="radioAnswer">NO</span>
      <input type="radio" value="No" class="radio">
    </div>
  </div>
  <div class="formField" id="ansYes">
    <label class="label">How are you doing?</label>
    <input type="text" class="input">
  </div>
  <input type="submit" value="Submit RSVP" id="submit">
</form>

Answer №3

If you want to create a toggling effect for the radio button backgrounds, simply using

$('.radioTransform', this).toggleClass('active');
will not suffice.

Firstly, consider that the code is already within a click event handler attached to $('.radioTransform'). By adding this as the second argument of

$('.radioTransform', this).toggleClass('active');
, you are instructing it to search for .radioTransform elements inside another .radioTransform. This causes the color not to change. Even if you remove this, it would toggle the class on every occurrence of .radioTransform.

Secondly, ensure to remove background: red from .radioTransform when it is inactive; otherwise, the change may not be visible.

var rsvpAns = $('.radioTransform');
rsvpAns.click(function() {
  $('.radio', this).prop('checked', !$('.radio', this).prop('checked')).change();
  var radioCheck = $('.radio', this).val();
  $(this).toggleClass('active');
  $(this).siblings('.radioTransform').toggleClass('active', !$(this).hasClass('active'));
  console.log(radioCheck);
  if (radioCheck == 'Yes') {
    $('#ansYes').fadeToggle(400);
  } else {
    $('#ansYes').fadeOut(400);
  }
});
.radio {
display: none;
}
#pushR {
margin-right: 25px;
}
.radioTransform {
width: 220px;
display: inline-block;
vertical-align: top;
background: #dbc8ca;
cursor: pointer;
padding: 15px 0;
}
.radioTransform {
/*background: red;*/
}
.radioAnswer {
font-family: 'Open Sans', sans-serif;
font-size: .9rem;
text-align: center;
}
#ansYes {
  display: none;
}

.radioTransform.active {
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="rsvpForm">
  <div class="formField">
    <div class="radioTransform" id="pushR">
      <span class="radioAnswer">YES</span>
      <input type="radio" value="Yes" class="radio">
    </div>
    <div class="radioTransform">
      <span class="radioAnswer">NO</span>
      <input type="radio" value="No" class="radio">
    </div>
  </div>
  <div class="formField" id="ansYes">
    <label class="label">How are you doing?</label>
    <input type="text" class="input">
  </div>
  <input type="submit" value="Submit RSVP" id="submit">
</form>

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

Javascript editing enhancement for real-time changes

Are there any tools for in-place editing of Javascript code? I'm looking for something similar to Firebug, which is great for instant CSS editing and previewing but doesn't have the capability to edit JavaScript directly. Is there a tool or addon ...

Encountered an issue while trying to set up mocks with $route in vue-test-utils

I am currently practicing test referencing by using a mock router. Here is the code I am working with: NestedRoute.vue <template> <div> <div>Nested Route</div> <div class="username"> {{ $route.params.username ...

Creating dynamic dropdowns with Ajax and HTML on the code side

I have developed a script that generates a drop-down menu and updates the .box div with a new color and image. Below is the HTML & Java code: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script> <div> ...

A guide on iterating through an array to extract the initial character from every string

Currently, my focus is on extracting the initial letter of each word in order to create an acronym. I have set up an array where all the capitalized words are stored, and now I need a way to extract those specific characters. To achieve this, I initially ...

Hovering over one element in Jquery triggers actions on multiple elements simultaneously

I'm working on a project where I have multiple cards, and I've implemented a hover effect using jQuery to make the images inside the cards bigger. However, I'm facing an issue where hovering over one card triggers the effect on all the other ...

The Material UI component successfully loads the options data list from the server response, however, it fails to return the selected value when an option

My goal is to dynamically populate my country and province select component based on server response data. The process begins with the user selecting a country, which triggers a request to the server using the selected country's id. The server respond ...

Unable to retrieve data with $.getJSON

I've hit a roadblock in finding the answer, so I created a temporary workaround - but unfortunately, it's not usable in the final file. Interestingly, when the JSON array is directly embedded in my JavaScript file, everything functions as expect ...

Discover the highest value within an array of objects, along with any numerical object attributes that have a value greater than zero

Considering an array of objects structured as follows: [{ "202201": { "WO": 900, "WS": 0, "SY": 0.915, "LY": 0.98, "CT": 75 }, "202202" ...

Tips for successfully transmitting verified user input within an input field on a webpage through the combination of Selenium and Python

Can you help me understand why I am facing difficulties in passing user input from a website to Selenium for automated typing in the search field? Is it possible to first enter the input, press enter, and then trigger selenium to send the input to the br ...

Is there a reason behind why this functionality is only applicable to a class component and not a functional one?

Essentially, I am working with multiple buttons and aiming for the user to be able to select more than one button at a time. I attempted to achieve this using a functional component by storing the button states as objects with the useState hook. While the ...

What are the best ways to condense this JavaScript snippet?

Seeking suggestions for enhancing my coding skills. How can this code be optimized for brevity and efficiency? var resultsConstructionYear = readCookie('constructionYear'); switch (resultsConstructionYear) { case 3: document.getEleme ...

RxJS Observables trigger the onCompleted function after completing a series of asynchronous actions

I have been attempting to design an observable that generates values from various asynchronous actions, particularly HTTP requests from a Jenkins server, which will notify a subscriber once all the actions are finished. However, it seems like there might b ...

Adding query parameters to the end of every link on a webpage

Wondering how to automatically add GET values to the end of each anchor href on a webpage? For instance, if you input google.com?label=12&id=12 I want to ensure that "?label=12&id=12" gets added to the end of every single href in an anchor tag on ...

Steps for removing an embed after a set time period

I've been using message.delete({timeout: 3000}) to remove messages with the prefix. Now I'm wondering how I can also delete the embed I sent after a certain amount of time. if (!args[0]) return message.channel.send({ embed: { color: 1677720 ...

Searching JSON Data for Specific String Value Using JavaScript

I am looking for a straightforward approach to search my JSON string using JavaScript. Below is the PHP code that generates my JSON String: <?php $allnames = array(); $res = mysql_query("SELECT first,last FROM `tbl_names`"); while ($row = mysql_fetch_ ...

Implementing callbacks in Chart.js for hover events

I would like to trigger a callback function when hovering over a specific part of the graph (donut chart). How can I achieve this? It seems that Chart.js does not have built-in support for callbacks, which is proving to be a challenge :) Below is my curre ...

How can you include a multi-layered array within another multi-layered array using TypeScript?

If we want to extend a two-dimensional array without creating a new one, the following approach can be taken: let array:number[][] = [ [5, 6], ]; We also have two other two-dimensional arrays named a1 and a2: let a1:number[][] = [[1, 2], [3, 4]]; let ...

Modify the Google Translate dropdown using programming techniques

Recently, I attempted to integrate the Google Translate dropdown feature into a website using the following code snippet: function googleTranslateElementInit() { new google.translate.TranslateElement({ pageLanguage: 'en' }, 'google ...

The functionality of Material UI Slider components becomes less responsive when enclosed and rendered in JSX

Why is the Material UI's Slider not working smoothly when called in JSX as shown below? SliderAndValue.js import { Slider } from "@material-ui/core"; import { useState } from "react"; import "./styles.css"; export const ...

What is the best way to parse a JSON file in Angular?

Can you please explain how to read a JSON file? I have been able to successfully read a JSON file using a controller, but when I try to read it from a factory, the content is null. Why is this happening? http://plnkr.co/edit/THdlp00GuSk1NS6rqe5k?p=preview ...