I wrote a html with 3 radio buttons. Each radio button is contained in a div container. I would like that if a radio button is checked, the background of the div container containing the checked radio-button should become blue, and the background the div containing the other unchecked radio-buttons should be white. I tried to achieve that with javascript and css, but it does not work. Could someone please help me to write correctly this javascript ?.
<!DOCTYPE html>
<html>
<style>
.stylingForCheckedRadioButton {
color: white;
background-color: blue;
border-style: solid;
border-width: thin;
border-color: grey;
margin-bottom: 7px;
width: 10%;
height: 50px;
border-radius: 6px;
}
.stylingForUnCheckedRadioButton {
color: black;
background-color: white;
border-style: groove;
border-width: thin;
border-color: #DCDCDC;
margin-bottom: 7px;
width: 10%;
height: 50px;
border-radius: 6px;
}
</style>
<script type="text/javascript">
function checkValue(containerId) {
const rbs = document.querySelectorAll('input[name = "radiobutton"]');
let selectedValue;
for (const rb of rbs) {
if (rb.checked) {
document.getElementById(containerId).style = "stylingForCheckedRadioButton";
}else{
document.getElementById(containerId).style = "stylingForUnCheckedRadioButton";
}
}
};
</script>
<body>
<h1>My Radio Buttons</h1>
<div class="stylingForUnCheckedRadioButton" id="container1">
<input id="radiobuttonId1" type="radio" value="radiobuttonId1" name="radiobutton" onclick="checkValue('container1')">
<label for="radiobuttonId1">Radio button 1</label>
</div>
<div class="stylingForUnCheckedRadioButton" id="container2">
<input id="radiobuttonId2" type="radio" value="radiobuttonId2" name="radiobutton" onclick="checkValue('container3')">
<label for="radiobuttonId2">Radio button 2</label>
</div>
<div class="stylingForUnCheckedRadioButton" id="container3">
<input id="radiobuttonId3" type="radio" value="radiobuttonId3" name="radiobutton" onclick="checkValue('container3')">
<label for="radiobuttonId3">Radio button 3</label>
</div>
</body>
</html>
this way...
const all_Radios = document.querySelectorAll('#container input[type=radio]');
set_Radios() // for page initialization
all_Radios.forEach( btRadio => btRadio.oninput = set_Radios )
function set_Radios()
{
all_Radios.forEach( bt =>
bt.closest('label').classList.toggle('checkedClass', bt.checked))
}
#container > label {
display : block;
color : black;
background-color : white;
border-style : groove;
border-width : thin;
border-color : #DCDCDC;
margin-bottom : 7px;
width : 10%;
height : 2em;
border-radius : 6px;
min-width : 10em;
line-height : 2em;
}
#container > label.checkedClass {
color : white;
background-color : blue;
border-style : solid;
border-color : grey;
}
<h1>My Radio Buttons</h1>
<div id="container">
<label>
<input name="radiobutton" type="radio" value="xxx" >
Radio button 1
</label>
<label>
<input name="radiobutton" type="radio" value="yyy" >
Radio button 2
</label>
<label>
<input name="radiobutton" type="radio" value="zzz" >
Radio button 3
</label>
</div>
You can use the event.target to get the parentNode of the input element to set the style using classList.replace(). Each click reset the classes of the parent elements to unchecked, then if the event.target is checked e.target.checked, replace the unchecked class with the checked class.
const rbs = document.querySelectorAll('input[name = "radiobutton"]');
// callback function setSel passing in the event from the listener
function setSel(e) {
// get parent element of the event target
let par = e.target.parentNode
// reset each input to unchecked before checking the event target
rbs.forEach(item => item.parentNode.classList.replace('stylingForCheckedRadioButton', 'stylingForUnCheckedRadioButton'))
// if the el is checked we replace the classList with
// the desired class that styles as checked
e.target.checked ?
par.classList.replace('stylingForUnCheckedRadioButton', 'stylingForCheckedRadioButton') :
null
}
// loop over the input nodeList and add event to each node
// in the list with a callback function 'setSel'
rbs.forEach(el => el.addEventListener('click', setSel))
.stylingForCheckedRadioButton {
background-color: red;
}
<!DOCTYPE html>
<html>
<style>
.stylingForCheckedRadioButton {
color: white;
background-color: blue;
border-style: solid;
border-width: thin;
border-color: grey;
margin-bottom: 7px;
width: 10%;
height: 50px;
border-radius: 6px;
}
.stylingForUnCheckedRadioButton {
color: black;
background-color: white;
border-style: groove;
border-width: thin;
border-color: #DCDCDC;
margin-bottom: 7px;
width: 10%;
height: 50px;
border-radius: 6px;
}
</style>
<script type="text/javascript">
</script>
<body>
<h1>My Radio Buttons</h1>
<div class="container stylingForUnCheckedRadioButton" id="container1">
<input id="radiobuttonId1" type="radio" value="radiobuttonId1" name="radiobutton">
<label for="radiobuttonId1">Radio button 1</label>
</div>
<div class="container stylingForUnCheckedRadioButton" id="container2">
<input id="radiobuttonId2" type="radio" value="radiobuttonId2" name="radiobutton">
<label for="radiobuttonId2">Radio button 2</label>
</div>
<div class="container stylingForUnCheckedRadioButton" id="container3">
<input id="radiobuttonId3" type="radio" value="radiobuttonId3" name="radiobutton">
<label for="radiobuttonId3">Radio button 3</label>
</div>
</body>
</html>
There are two main issues here. First, you should use the className attribute instead of style to change the element class.
Secondly, in your function, JavaScript is setting the color of the divs based on the last value in the rbs nodeList. This means that your intended div will be styled according to whether or not the last radio button is checked. To change this, query the DOM for a list of all the divs then check each div according to its corresponding radio button based on index.
function checkValue() {
const rbs = document.querySelectorAll('input[name = "radiobutton"]');
rbs.forEach((rb, i) => {
let div = document.getElementById(`container${i + 1}`);
div.className = rb.checked ? 'stylingForCheckedRadioButton' : 'stylingForUnCheckedRadioButton';
})
};
.stylingForCheckedRadioButton {
color: white;
background-color: blue;
border-style: solid;
border-width: thin;
border-color: grey;
margin-bottom: 7px;
width: 10%;
min-width: 150px;
height: 50px;
border-radius: 6px;
}
.stylingForUnCheckedRadioButton {
color: black;
background-color: white;
border-style: groove;
border-width: thin;
border-color: #DCDCDC;
margin-bottom: 7px;
width: 10%;
min-width: 150px;
height: 50px;
border-radius: 6px;
}
<!DOCTYPE html>
<html>
<body>
<h1>My Radio Buttons</h1>
<div class="stylingForUnCheckedRadioButton" id="container1">
<input id="radiobuttonId1" type="radio" value="radiobuttonId1" name="radiobutton" onclick="checkValue()">
<label for="radiobuttonId1">Radio button 1</label>
</div>
<div class="stylingForUnCheckedRadioButton" id="container2">
<input id="radiobuttonId2" type="radio" value="radiobuttonId2" name="radiobutton" onclick="checkValue()">
<label for="radiobuttonId2">Radio button 2</label>
</div>
<div class="stylingForUnCheckedRadioButton" id="container3">
<input id="radiobuttonId3" type="radio" value="radiobuttonId3" name="radiobutton" onclick="checkValue()">
<label for="radiobuttonId3">Radio button 3</label>
</div>
</body>
</html>
I recommend to read some topics on DRY.
// All the radio buttons
const radios = document.querySelectorAll('.radio')
// Function to toggle active class
function handleRadioClick(e) {
// Remove previous active class
for (let i = 0; i < radios.length; i++) {
radios[i].parentNode.classList.remove('active')
}
// Add current active class to parent container
e.target.parentNode.classList.add('active')
}
// Listen for the click event on radios
for (let i = 0; i < radios.length; i++) {
radios[i].addEventListener('click', handleRadioClick, false);
}
.container {
color: black;
background-color: white;
border-style: groove;
border-width: thin;
border-color: #DCDCDC;
margin-bottom: 7px;
width: 10%;
height: 50px;
border-radius: 6px;
}
.container.active {
color: white;
background-color: blue;
border-style: solid;
border-width: thin;
border-color: grey;
margin-bottom: 7px;
width: 10%;
height: 50px;
border-radius: 6px;
}
<div class="container">
<input class="radio" id="btn1" type="radio" value="btn1" name="radio">
<label for="btn1">Radio button 1</label>
</div>
<div class="container">
<input class="radio" id="btn2" type="radio" value="btn2" name="radio">
<label for="btn2">Radio button 2</label>
</div>
<div class="container">
<input class="radio" id="btn3" type="radio" value="btn3" name="radio">
<label for="btn3">Radio button 3</label>
</div>
Related
I want to display the tooltip only when I hover over a checked radio button.
When hovered on the radio button I'm trying to check
$(this).is(':checked') == true
But the tooltip is displayed only when hovered on "Yes". What am I doing wrong here?.
Any suggestions are highly appreciated. Thanks in advance. :)
$("input[name^='radioBtn']").hover(function () {
if(($(this).is(':checked')) == true){
var text= "Hello";
$(".displayContents").append(text);
}
});
.radioHover:hover ~ .displayContents{
visibility: visible;
}
.displayContents{
visibility: hidden;
background-color: white;
border: 2px solid black;
position: absolute;
z-index: 1;
border-radius: 6px;
padding: 5px 0;
width: 350px;
/* border-spacing: 35px; */
text-align: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<div>
<div>
<input type="radio" name="radioBtn radioHover" value="true" id="radioYes" class="radioBtn radioHover"/><br />
<div class="displayContents"></div>
<span>Yes</span>
</div>
<div>
<input type="radio" name="radioBtn radioHover" value="true" id="radioNo" class="radioBtn"/><br />
<div class="displayContents"></div>
<span>No</span>
</div>
</div>
It is not necessary to use jQuery to achieve your desired goal. It is enough to aim the :hover pseudo-class at the :checked pseudo-class, in the css. Like this:
.radioHover:checked:hover ~ .displayContents {
visibility: visible;
}
For unique content of each radio button, use id #radioYes and #radioNo with operator ~.
$("#radioYes ~ .displayContents").text("Hello Yes");
$("#radioNo ~ .displayContents").text("Hello No");
.radioHover:checked:hover ~ .displayContents {
visibility: visible;
}
.displayContents {
visibility: hidden;
background-color: white;
border: 2px solid black;
position: absolute;
z-index: 1;
border-radius: 6px;
padding: 5px 0;
width: 350px;
/* border-spacing: 35px; */
text-align: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<div>
<div>
<input type="radio" name="radioBtn" value="true" id="radioYes" class="radioBtn radioHover" /><br />
<div class="displayContents"></div>
<span>Yes</span>
</div>
<div>
<input type="radio" name="radioBtn" value="true" id="radioNo" class="radioBtn radioHover" /><br />
<div class="displayContents"></div>
<span>No</span>
</div>
</div>
First of all, you put radioHover into name attribute.
Anyway, you should set radioHover class on the checked button only, like so:
$("input[name='radioBtn']").hover(function () {
this.classList.toggle("radioHover", this.checked);
if($(this).is(':checked') == true){
var text= "Hello";
$(".displayContents").append(text);
}
});
.radioHover:hover ~ .displayContents{
visibility: visible;
}
.displayContents{
visibility: hidden;
background-color: white;
border: 2px solid black;
position: absolute;
z-index: 1;
border-radius: 6px;
padding: 5px 0;
width: 350px;
/* border-spacing: 35px; */
text-align: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<div>
<div>
<input type="radio" name="radioBtn" value="true" id="radioYes" class="radioBtn"/><br />
<div class="displayContents"></div>
<span>Yes</span>
</div>
<div>
<input type="radio" name="radioBtn" value="false" id="radioNo" class="radioBtn"/><br />
<div class="displayContents"></div>
<span>No</span>
</div>
</div>
You had some typos and some misunderstandings. The radioHover class was in the name field, was missing in the class for the 'no' radio. Additionally, you have 2 different . displayContents elements. The way to target the one associated with the radio is via the .closest(selector).find(selector) combo. I didn't think you wanted to actually append the same HTML continuously, so I changed that to .html().
Finally, I added the 'change' event in the mix - that way you'll get your value on hover and on click (if checked). Reason being, you are hovering over the element when you click it. Yet the hover didn't update when the state went from not-checked to checked. Now it does
$("input[name='radioBtn']").on('hover, change', function() {
if ($(this).is(':checked')) {
$(this).closest('div').find(".displayContents").html('Hello from ' + $(this).val());
}
});
.radioHover:checked:hover~.displayContents {
visibility: visible;
}
.displayContents {
visibility: hidden;
background-color: white;
border: 2px solid black;
position: absolute;
z-index: 1;
border-radius: 6px;
padding: 5px 0;
width: 350px;
/* border-spacing: 35px; */
text-align: left;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<div>
<div>
<input type="radio" name="radioBtn" value="yes" id="radioYes" class="radioBtn radioHover" /><br />
<div class="displayContents"></div>
<span>Yes</span>
</div>
<div>
<input type="radio" name="radioBtn" value="no" id="radioNo" class="radioBtn radioHover" /><br />
<div class="displayContents"></div>
<span>No</span>
</div>
</div>
I have my website code below, however my problem is not with its functionality rather its with its appearance
var name;
var nameFormat = true;
var totalRight=0;
var welcomeName
$("#welcome2").hide();
$("#welcome2-0").hide();
$('form').hide();
$("#MYsubmit").hide();
var score;
function submission() {
var name = document.getElementById("textbox").value;
if (name.length > 0) {
alert("Welcome " + name);
$("#name").fadeOut(1000);
$("#welcome").fadeOut(1000);
$("#welcome2").show();
$("#welcome2-0").show();
$('MYsubmit').show();
$('form').show();
welcomeName=document.getElementById("welcome3-1").innerHTML +="Welcome "+name+"!"+"Good Luck!";
} else {
nameFormat == false;
alert("Please enter the name again");
}
}
var welcomeName=document.getElementById("Question1").innerHTML +="1. How long does it take the average person to fall asleep?";
var welcomeName=document.getElementById("Question2").innerHTML +="2.How many eggs does the average american eat per year?";
var welcomeName=document.getElementById("Question3").innerHTML +="3.How many taste buds does the average american have?";
var welcomeName=document.getElementById("Question4").innerHTML +="4.What is the average lifespan of a squirrel?";
var welcomeName=document.getElementById("Question5").innerHTML +="5.on average __% of all restaurant meals include potato chips";
function finalsubmit() {
if(document.getElementById('correctAnswer-1').checked) {
totalRight=totalRight+1;
}
if(document.getElementById('correctAnswer-2').checked) {
totalRight=totalRight+1;
}
if(document.getElementById('correctAnswer-3').checked) {
totalRight=totalRight+1;
}
if(document.getElementById('correctAnswer-4').checked) {
totalRight=totalRight+1;
}
if(document.getElementById('correctAnswer-5').checked) {
totalRight=totalRight+1;
}
document.getElementById("score").innerHTML +="RESULT for "+name+"You Scored "+totalRight+" out of 5!"+"<br>";
score=document.getElementById("ans").innerHTML +="You scored "+totalRight+" out of 5";
if(totalRight==5){
document.getElementById("score").innerHTML +="You score 5/5 PERFECT!";
}
}
/*
$(document).ready(function(){
$("#hint1").mouseover(function(){
$("#hint1").
});
$("#hint1").mouseout(function(){
$("#hint1").
});
});
*/
$(document).ready(function(){
$('#hint1').hover(function() {
$(this).text("7Minutes");
},
function() {
$(this).text("[HINT]");
});
});
$(document).ready(function(){
$('#hint2').hover(function() {
$(this).text("263Eggs");
},
function() {
$(this).text("[HINT]");
});
});
$(document).ready(function(){
$('#hint3').hover(function() {
$(this).text("10,000");
},
function() {
$(this).text("[HINT]");
});
});
$(document).ready(function(){
$('#hint4').hover(function() {
$(this).text("7Years");
},
function() {
$(this).text("[HINT]");
});
});
$(document).ready(function(){
$('#hint5').hover(function() {
$(this).text("7%");
},
function() {
$(this).text("[HINT]");
});
});
#welcome{
top:30px;
left: 30px;
color: antiquewhite;
border: 2px solid darkblue;
background: darkblue;
padding: 25px;
}
#name{
top:30px;
left: 500px;
color: antiquewhite;
background: darkblue;
border: 25px solid darkblue;
}
body {
background-color: lightblue;
color: white;
}
#welcome2{
text-align: center;
color: antiquewhite;
background: darkblue;
border: 25px solid darkblue;
}
#welcome3-1{
top:30px;
left: 500px;
color: Aqua;
background:darkblue;
border: 25px solid darkblue;
}
#welcome2-0{
text-align: center;
color: antiquewhite;
background: darkblue;
border: 25px solid darkblue;
}
.Question{
text-align: left;
color: antiquewhite;
background: darkblue;
border: 25px solid darkblue;
}
.hints{
color: aquamarine;
background: darkblue;
border: 25px solid darkblue;
}
.quiz{
background: darkblue;
}
#ans{
text-align: left;
border: 25px solid darkblue;
background: darkblue;
color:red;
}
#score{
background-color: yellow;
color:red;
background-size: 100px 100px;
}
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Welcome!</title>
<link rel="stylesheet" href="includes/styles.css" type="text/css" media="screen" />
</head>
<p>
<body>
<div id="welcome"><b>Welcome to the Myanmar Trivia Quiz</b><br> please enter your name and click on "Begin Quiz" to start</div>
<div id="name"><b>Name:</b>
<input type="text" id="textbox">
<button id=”myButton” type="button" onclick="submission()">submit</button>
</div>
<h1 id="welcome2">Myanmar Trivia Quiz </h1>
<div id="welcome2-0">Test your Demographic Knowledge<br>---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------</div>
<div id="welcome3-1"><b></b></div>
<div id="ans"><h3></h3></div>
<form class="quiz">
<div id="Question1" class="Question"><b></b></div>
<input type="radio" name="radiobutton" value="7Minutes" id="correctAnswer-1" class="Answer"> 7 Minutes<br>
<input type="radio" name="radiobutton" value="5Minutes" >5 Minutes<br>
<input type="radio" name="radiobutton" value="20Minutes" >20 Minutes <br>
<input type="radio"name="radiobutton" value="14Minutes" >14 Minutes <br>
<div id="hint1" class="hints">[HINT]</div>
</form>
<form class="quiz">
<div id="Question2" class="Question"><b></b></div>
<input type="radio" name="radiobutton" value="263Eggs" id="correctAnswer-2">263 eggs a year<br>
<input type="radio" name="radiobutton" value="23Eggs">23 eggs a year<br>
<input type="radio" name="radiobutton" value="100Eggs">100 eggs a year<br>
<input type="radio" name="radiobutton" value="45Eggs">45 eggs a year<br>
<div id="hint2" class="hints">[HINT]</div>
</form>
<form class="quiz">
<div id="Question3" class="Question"><b></b></div>
<input type="radio" name="radiobutton" value="10,000" id="correctAnswer-3">10,000<br>
<input type="radio" name="radiobutton" value="4000">4000<br>
<input type="radio" name="radiobutton" value="20,000">20,000<br>
<input type="radio" name="radiobutton" value="537">537<br>
<div id="hint3" class="hints">[HINT]</div>
</form>
<form class="quiz">
<div id="Question4" class="Question"><b></b></div>
<input type="radio" name="radiobutton" value="7Years" id="correctAnswer-4"> 7 Years<br>
<input type="radio" name="radiobutton" value="5Years">5 Years<br>
<input type="radio" name="radiobutton" value="20Years">20 Years <br>
<input type="radio" name="radiobutton" value="14Years">14 Years <br>
<div id="hint4" class="hints">[HINT]</div>
<form class="quiz">
<div id="Question5" class="Question"><b></b></div>
<input type="radio" name="radiobutton" value="7%" id="correctAnswer-5"> 7%<br>
<input type="radio" name="radiobutton" value="5%">5%<br>
<input type="radio" name="radiobutton" value="20%">20%<br>
<input type="radio" name="radiobutton" value="14%">14%<br>
<div id="hint5" class="hints">[HINT]</div>
<br>
<br>
<button id=”MYsubmit” type="button" onclick="finalsubmit()">submit</button>
<div id="score"></div>
<div id="COPYRIGHT">Copyright © 2019. All rights reserved</div>
</form>
</body>
<script src="includes/scripts.js"></script>
</html>
. I would like the dark blue backgrounds touching each other, and I would like my radio buttons moved so they are below the answers,also I would like to do the same with the hint, and welcome comment. Im new with css so i apologize if its done poorly, im having a hard time figuring this one out and would appreciate any help. thank you guys alot!
Maybe you can use tooltip? Example from w3schools
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted black;
}
.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: black;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px 0;
/* Position the tooltip */
position: absolute;
z-index: 1;
}
.tooltip:hover .tooltiptext {
visibility: visible;
}
<div class="tooltip">HINT
<span class="tooltiptext">Put your hint here</span>
</div>
I'm pretty sure you should just use Tooltip instead of mouseover ^^
JQuery Tooltip
$("#hint1").tooltip();
with title as attribute for the texts.
Here's the Codepen Demo
I found the answer, skipped the animations but got it working using this code below:
$(document).ready(function(){
$('#hint2').hover(function() {
$(this).text("hover text");
},
function() {
$(this).text("back to origonal");
});
});
In the snippet below you will see that I am styling a radio button to look like a button. I am wanting these buttons to work just as the radio button would in its normal state. Right now both radio buttons are taking on the active class from my javascript on page load. This should only happen if they are selected.
Also, the fadeToggle from the if-statement that produces the extra input under the radio buttons is functioning as if the radio buttons are checkboxes. I have to click on the same button twice to de-activate it. I think this is based on the issue above.
Does anyone have any ideas what I am doing wrong?
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>
You don't need Javascript at all for this - only some intelligent CSS and a slight restructuring of your markup. This change will even increase the semantic value and accessibility of your solution.
I have only added Javascript for some console.logging so you see the snippet works.
Please note that in order to make radio buttons work like expected, they need to share the name attribute, otherwise both can be "on".
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>
Your if condition block only works when you clicked yes button. Then what if you clicked No, for this condition you can have else statement. And here in this code radioTransform div don't have active class on load.
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>
In order to achieve the toggling effect of the radio button with the backgrounds, $('.radioTransform', this).toggleClass('active'); will not be enough.
First, taking into consideration it is already inside a click handler which is attached to $('.radioTransform'), when you add this as second argument of $('.radioTransform', this).toggleClass('active'); you are telling it to look for .radioTransforms inside a .radioTransform, cause you are setting .radioTransform as the context of the selector, that's why it does not change color. And even if you remove this, you would be toggling the class for every .radioTransform there is (how many times did I write radioTransform?:) )
Second, remove background: red from .radioTransform when it is not active, else you will never see it happen
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>
I am building a form to measure carpets dimension. In the form there is radio button which user can choose type of carpet. I want to make when the radio button checked, the image of the carpet change based on the selected radio button.
1st image : radio button to choose carpet size
2nd image: carpet change based on selected radio button
Below is the code:
<form class="carpet-detail text-center container">
<p class="text-center">Upload your carpet’s photo here :</p>
<div class="upload-carpet">
<div id="image-preview">
<input id="image-upload" name="image" type="file">
</div>
<label for="image-upload" id="image-label">Choose File</label>
</div>
<p class="carpet-name">Carpet 1</p>
<p>Choose your carpet shape :</p>
<div class="carpet-shape">
<div class="choose-carpet">
<input checked class="radio-shape" id="carpet-shape-1" name="carpet-shape" type="radio"> <label class="choose-shape" for="carpet-shape-1">Rectangular</label>
</div>
<div class="choose-carpet">
<input class="radio-shape" id="carpet-shape-2" name="carpet-shape" type="radio"> <label class="choose-shape" for="carpet-shape-2">Square</label>
</div>
<div class="choose-carpet">
<input class="radio-shape" id="carpet-shape-3" name="carpet-shape" type="radio"> <label class="choose-shape" for="carpet-shape-3">Round</label>
</div>
<div class="choose-carpet">
<input class="radio-shape" id="carpet-shape-4" name="carpet-shape" type="radio"> <label class="choose-shape" for="carpet-shape-4">Oval</label>
</div>
</div>
<p>Please insert your carpet size :</p>
<img alt="carpet rectangle" class="carpet-icon" height="116" src="img/icons/carpet-rectangle.svg" width="194">
<div class="grid-x grid-padding-x carpet-size">
<div class="small-6 cell text-left">
<p>Width :</p>
</div>
<div class="small-6 cell text-right">
<p>/sqft</p>
</div>
<div class="small-12 cell">
<div class="input-group plus-minus-input">
<div class="input-group-button">
<button type="button" class="button circle" data-quantity="minus" data-field="quantity-width">
<img src="img/icons/size-minus.svg" alt="minus" width="11" height="11">
</button>
</div>
<input class="input-group-field" type="number" name="quantity-width" value="0">
<div class="input-group-button">
<button type="button" class="button circle" data-quantity="plus" data-field="quantity-width">
<img src="img/icons/size-plus.svg" alt="minus" width="11" height="11">
</button>
</div>
</div>
</div>
</div>
<div class="grid-x grid-padding-x carpet-size">
<div class="small-6 cell text-left">
<p>Length :</p>
</div>
<div class="small-6 cell text-right">
<p>/sqft</p>
</div>
<div class="small-12 cell">
<div class="input-group plus-minus-input">
<div class="input-group-button">
<button type="button" class="button circle" data-quantity="minus" data-field="quantity-length">
<img src="img/icons/size-minus.svg" alt="minus" width="11" height="11">
</button>
</div>
<input class="input-group-field" type="number" name="quantity-length" value="0">
<div class="input-group-button">
<button type="button" class="button circle" data-quantity="plus" data-field="quantity-length">
<img src="img/icons/size-plus.svg" alt="plus" width="11" height="11">
</button>
</div>
</div>
</div>
</div>
</form>
You can use the jquery's .change event to do this.
First assign the attribute valueto the radios.
<input class="radio-shape" value="Square" id="carpet-shape-2" name="carpet-shape" type="radio">
Then use the change following juery to trigger the event.
$('input:radio[name="carpet-shape"]').change(
function(){
var $src = "";
if ($(this).val() == 'Square') {
$src = "img/icons/carpet-square.svg";
}
else if ($(this).val() == 'Rectangle') {
$src = "img/icons/carpet-rectangle.svg";
}
else if ($(this).val() == 'Round') {
$src = "img/icons/carpet-round.svg";
}
else{
$src = "img/icons/carpet-oval.svg"
}
$('.carpet-icon').attr('src',$src);
});
Here is a full working jsfiddle
For more information on change event, checkout the jQuery documentation on it.
You just need a JavaScript or jQuery event listener.
//jQuery version
$('#radio1').on('click', function() {
$('#image1').attr('src', 'myNewImage.jpg');
});
//Vanilla JavaScript
document.getElementById('radio1').addEventListener('click', null,
function() {
document.getElementsById('radio1').setAttribute('src', 'myNewImage.jpg');
});
You'd obviously need to add one for each radio button.
You can change the image by using CSS selectors like ~ , +.
By this method, if the checkbox is checked we can select the siblings by using the ~, + selector.
Then we can apply the styles to the selected siblings.
Here I have given the code snippet and working demo.
CSS CODE
.output-shape {
width: 200px;
}
//Square
#square ~ .output-shape{
width: 200px;
}
//Rectangle
#rectangle:checked ~ .output-shape{
width: 280px;
}
//Circle
#circle:checked ~ .output-shape{
border-radius: 50%;
width: 200px;
}
HTML CODE
// Input Field
<input type="radio" name="radio" id="circle" checked>
<input type="radio" name="radio" id="rectangle">
<input type="radio" name="radio" id="square">
// Label Field
<label for="circle">circle</label>
<label for="rectangle">Rectangle</label>
<label for="square">square</label>
// OUTPUT
<div class="output-shape"></div>
Working DEMO
body, html {
font-family: sans-serif;
}
.box-overlay {
background-color: coral;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: -1;
}
.box-content {
background-color: #fff;
max-width: 600px;
text-align: center;
border-radius: 15px;
min-height: 350px;
padding: 15px;
margin-left: auto;
margin-right: auto;
margin-top: 100px;
box-shadow: 0 0 20px rgba(0,0,0,0.5);
}
.output-shape {
width: 200px;
height: 200px;
background-color: white;
border: 1px solid gray;
margin-left: auto;
margin-right: auto;
margin-top: 20px;
margin-bottom: 20px;
}
input {
display: none;
}
label {
padding: 10px;
border: 1px solid gray;
display: inline-block;
border-radius: 5px;
text-transform: uppercase;
margin-top: 5px;
margin-bottom: 5px;
margin-left: 5px;
margin-right: 5px;
}
.option-name {
font-size: 20px;
margin-left: 10px;
margin-right: 10px;
text-transform: uppercase;
}
/* Circle */
label[for="circle"] {
color: dodgerblue;
border-color: dodgerblue;
}
#circle:checked ~ .box-content [for="circle"] {
color: #fff;
background-color: dodgerblue;
}
#circle:checked ~ .box-content .output .option-name{
color: dodgerblue;
}
#circle:checked ~ .box-content .output .option-name:before{
content:"Circle" !important;
}
#circle:checked ~ .box-content .output .output-shape{
border-radius: 50%;
background-color: dodgerblue;
border-color: dodgerblue;
}
#circle:checked ~ .box-overlay {
background-color: dodgerblue !important;
}
/* Rectangle */
label[for="rectangle"] {
color: darkorange;
border-color: darkorange;
}
#rectangle:checked ~ .box-content [for="rectangle"] {
color: #fff;
background-color: darkorange;
}
#rectangle:checked ~ .box-content .output .option-name{
color: darkorange;
}
#rectangle:checked ~ .box-content .output .option-name:before{
content:"rectangle" !important;
}
#rectangle:checked ~ .box-content .output .output-shape{
width: 280px;
background-color: darkorange;
border-color: darkorange;
}
#rectangle:checked ~ .box-overlay {
background-color: darkorange !important;
}
/* Square */
label[for="square"] {
color: #3FBB76;
border-color: #3FBB76;
}
#square:checked ~ .box-content [for="square"] {
color: #fff;
background-color: #3FBB76;
}
#square:checked ~ .box-content .output .option-name{
color: #3FBB76;
}
#square:checked ~ .box-content .output .option-name:before{
content:"square" !important;
}
#square:checked ~ .box-content .output .output-shape{
background-color: #3FBB76;
border-color: #3FBB76;
}
#square:checked ~ .box-overlay {
background-color: #3FBB76 !important;
}
.box-overlay, .output-shape, .option-name:before {
transition: all linear 0.50s;
-webkit-transition: all linear 0.50s;
-o-transition: all linear 0.50s;
-moz-transition: all linear 0.50s;
}
#media (max-width: 768px) {
.box-content {
margin-top: 20px;
}
}
#media (min-width: 769px) {
body, html {
/* height: 100%;*/
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>CSS Shape transition </title>
</head>
<body>
<div class="box">
<input type="radio" name="radio" id="circle" checked>
<input type="radio" name="radio" id="rectangle">
<input type="radio" name="radio" id="square">
<div class="box-content">
<label for="circle">circle</label>
<label for="rectangle">Rectangle</label>
<label for="square">square</label>
<h4 class="output">
You have selected
<div class="output-shape"></div>
<span class="option-name"></span>
</h4>
</div>
<div class="box-overlay"></div>
</div>
</body>
</html>
Note: To achieve this input element need to present above to the image element.
first you need to see which radio input was checked and then perform some changes on the icon image to show the desired image : I believe you are looking for something like the code below, I haven't tested it so you may
want to tweak it a little bit..
$('.carpet-detail').on('click', 'input', changeImage);
// delegate the the listening to the form so you don't have
// to listen to every radio button, then filter only radio
function changeImage(evt){
// create a function that can receive the event object by
// providing a parameter
var imageId = evt.target.id;
// store the id of the target element in var
switch(imageId){
// a simple switch statement to see which radio was checked
case 'carpet-shape-2':
$('.carpet-icon').attr("src","carpet-shape-2.jpg");
break;
// set the correct image for the chosen radio
case 'carpet-shape-3':
$('.carpet-icon').attr("src","carpet-shape-3.jpg");
break;
case 'carpet-shape-4':
$('.carpet-icon').attr("src","carpet-shape-4.jpg");
default:
$('.carpet-icon').attr("src","default-image.jpg");
}
}
I am creating a custom form but have hit a snag: The Radio buttons; when you click on them in the unchecked status the do not check. They will check if click the associated Div and the will also uncheck when checked. I have tried to extend the JS to the Label and It still does not work. And so...
How do I get a custom radio button to check and/or what do i need to do to get this to function?
Here is the relevant Code:
function check(checkbox) {
if (document.getElementById(checkbox).checked == false) {
document.getElementById(checkbox).checked = true;
} else {
document.getElementById(checkbox).checked = false;
}
}
.title {
display: inline;
position: relative;
top: 2px;
font-family: "Arial";
color: #fff;
font-size: 18px;
padding: 0px;
margin: 0px;
margin-top: 0px;
margin-right: 0px;
margin-bottom: 0px;
margin-left: 0px;
border-collapse: collapse;
font-stretch: ultra-condensed;
}
input[type="radio"] {
display: none;
}
[type="radio"] + label {
width: 10px;
height: 10px;
}
[type="radio"] + label {
background-color: #A3D5FF;
border: 1px solid #A3D5FF;
padding: 9px;
border-radius: 20px;
display: inline-block;
position: relative;
margin-right: 30px;
}
[type="radio"]:checked + label {
background-color: #0088A8;
;
border: 3px solid #fff;
height: 5.75px;
width: 5.75px;
color: #243441;
}
input[type="radio"] + label {
cursor: pointer;
font-size: 1em;
float: right;
position: relative;
right: -27px;
}
.chk {
background: #009FC2;
width: 265px;
height: 30px;
margin: 5px;
padding: 5px;
border-radius: 5px;
}
.chk:hover {
background: #0088A8;
}
HTML
<div class="chk" onClick="check('f-unlimited')">
<h3 class="title">
Unlimited
</h3>
<input id="f-unlimited" name="format" type="radio" value="f-unlimited" checked="checked"></input>
<label for="f-unlimited"></label>
</div>
<div class="chk" onClick="check('f-expandedFormat')">
<h3 class="title">
Expanded Format
</h3>
<input id="f-expandedFormat" name="format" type="radio" value="f-expandedFormat"></input>
<label for="f-expandedFormat"></label>
</div>
<div class="chk" onClick="check('f-standardLegal')">
<h3 class="title">
Standard Legal
</h3>
<input id="f-standardLegal" name="format" type="radio" value="f-standardLegal"></input>
<label for="f-standardLegal"></label>
</div>
</div>
Additional note: I am running almost identical code for my checkboxes and they are working perfectly.
The problem is in your check function. When you click on the div it fires to reverse the check state. When you click the check itself, the check state is reversed, then the check function runs and reverses the state again. You need to cancel event propagation when the check itself is clicked.
noted, previous answer was in jquery, please see below for vanilla
javascript :
function checkboxClicked() {
event.stopPropagation();
event.preventDefault();
}
function check(checkbox) {
if (document.getElementById(checkbox).checked == false) {
document.getElementById(checkbox).checked = true;
} else {
document.getElementById(checkbox).checked = false;
}
}
html :
<div class="chk" onClick="check('f-unlimited')">
<h3 class="title">
Unlimited
</h3>
<input onclick="checkboxClicked()" id="f-unlimited" name="format" type="radio" value="f-unlimited" checked="checked"></input>
<label for="f-unlimited"></label>
</div>
<div class="chk" onClick="check('f-expandedFormat')">
<h3 class="title">
Expanded Format
</h3>
<input onclick="checkboxClicked()" id="f-expandedFormat" name="format" type="radio" value="f-expandedFormat"></input>
<label for="f-expandedFormat"></label>
</div>
<div class="chk" onClick="check('f-standardLegal')">
<h3 class="title">
Standard Legal
</h3>
<input onclick="checkboxClicked()" id="f-standardLegal" name="format" type="radio" value="f-standardLegal"></input>
<label for="f-standardLegal"></label>
</div>