Hiding radio button name/label along with button - javascript

I'm trying to hide a radio button when another button is selected. I managed to hide the actual button but I can't find a way to hide the label/ name. This code below only hides the button.
document.getElementById('lights').style.display = 'none';
Code below is the actual button. I even trid putting the name in label tags.
Lights
<input type="radio" onclick="javascript:yesnoCheck();" name="yesno" id="lights" />

You can add the "lights" word inside a label or a span then use "previousElementSibling" to hide it.
const radioBtn = document.getElementById('lights');
radioBtn.style.display = 'none';
radioBtn.previousElementSibling.style.display = 'none';
<span>Lights</span>
<input type="radio" onclick="javascript:yesnoCheck();" name="yesno" id="lights" />

A better usability pattern would deemphasize it visually. Listen for clicks to the parent element and set a CSS class. Target the radio group's :checked attribute. Apply a style to the + next element, a label with a for= attribute.
let selector = "fieldset";
let parent = document.querySelector(selector);
parent.onclick = function(event) {
let element = event.target;
// if click child, deemphasize
if (element.nodeName.toLowerCase() != selector) {
element.closest(selector).classList.add("taint");
}
}
.taint {
border: 0.125em dotted red;
}
.taint input[type=radio]:not(:checked)+label {
opacity: 0.25;
}
<fieldset>
<input type="radio" name="hue" id="light" /><label for="light">Light</label>
<input type="radio" name="hue" id="dark" /><label for="dark">Dark</label>
</fieldset>

Related

Using data attribute on radio button group to show text

The outcome I am after is that when a user sends keyboard focus to a radio button group and navigates to each radio button using the arrow keys, or, clicks a radio button with a pointing device (mouse), the data-attribute value for that radio button is set to an element (h2).
I have got this far , and am now stuck. I am using an ID for the example, however, I would prefer to use a class or the data-set="X".
The code below sets the first data-col value but not the second.
Thanks for any help as I learn so much from Stackoverflow. I need this in vanilla JS and not jQuery, sorry.
<p>
<label for="">The colour is Green
<input type="radio" name="bob" data-col="Green" data-set="Green" id="demo3">
</label>
<label for="">The colour is Blue
<input type="radio" name="bob" data-col="Blue" data-set="Blue" id="demo3">
</label>
</p>
<h2 id="chjkl"></h2>
document.getElementById('demo3').onclick = function changeClk() {
const setCol = document.querySelector('#demo3');
document.getElementById('chjkl').innerHTML = setCol.dataset.col
}
document.getElementById('demo3').onfocus = function changeFoc() {
const setCol = document.querySelector('#demo3');
document.getElementById('chjkl').innerHTML = setCol.dataset.col
}
Use the event.target to get the dataset.
In the example below I change the color of your h2 elements background. Note that I am passing the event into the function and calling the function in the eventListener.
Also rather than having two eventListeners, I add a class to the radio button and then query that using querySelectorAll(). Then run the nodeList through a loop and check the event.target when the eventListener is fired.
An issue with your code is you have more than one element with the same ID. You should not have more than one element with any unique ID. ID must be unique to only one single element.
let radio = document.querySelectorAll('.radio')
let target = document.getElementById('chjkl')
function changeColor(e) {
target.style.backgroundColor = e.target.dataset.col
target.textContent = e.target.dataset.col
}
radio.forEach(btn => {
btn.addEventListener('focus', changeColor)
})
#chjkl {
display: flex;
justify-content: center;
letter-spacing: 1.3rem;
}
<p>
<label for="">The colour is Green
<input type="radio" name="bob" data-col="Green" class="radio">
</label>
<label for="">The colour is Red
<input type="radio" name="bob" data-col="Red" class="radio">
</label>
<label for="">The colour is Blue
<input type="radio" name="bob" data-col="Blue" class="radio">
</label>
<label for="">The colour is Orange
<input type="radio" name="bob" data-col="Orange" class="radio">
</label>
</p>
<h2 id="chjkl"></h2>

How can I get the value of the radio button after click

How will I get the value of the radio button after clicked on the button?
document.getElementById('btnKnop1').addEventListener('click', function(){
var kleuren = document.querySelectorAll('input[type=radio');
for (var i in kleuren) {
kleuren[i].onclick = function(){
document.getElementById('divResult'). innerHTML =
'Gekozen kleur: ' + this.value;
}
}
});
<input type="radio" name="radioGroup" value="rood" checked />Rood</br />
<input type="radio" name="radioGroup" value="blauw" />Blauw</br />
<input type="radio" name="radioGroup" value="geel" />Geel</br />
<input type="radio" name="radioGroup" value="groen" />Groen</br />
<button id="btnKnop1">Check de waarde!</button>
<div id="divResult"></div>
Now it depends on click on the radio button, but I'd to depend on click on the button
The issue seems to be be the inner click event on the radio button. If you change the loop to an if statement checking if it's checked then you can output the value on the button click:
document.getElementById('btnKnop1').addEventListener('click', function(){
var kleuren = document.querySelectorAll('input[type=radio');
for (var i in kleuren) {
if (kleuren[i].checked === true) {
document.getElementById('divResult'). innerHTML =
'Gekozen kleur: ' + kleuren[i].value;
}
}
});
<input type="radio" name="radioGroup" value="rood" checked />Rood</br>
<input type="radio" name="radioGroup" value="blauw" />Blauw</br>
<input type="radio" name="radioGroup" value="geel" />Geel</br>
<input type="radio" name="radioGroup" value="groen" />Groen</br>
<button id="btnKnop1">Check de waarde!</button>
<div id="divResult"></div>
First of all, please consider using english-named variables, it will improve readability by a lot.
Second of all, line
var kleuren = document.querySelectorAll('input[type=radio');
has a typo, it's missing a closing square bracket - ].
To check a checkbox/radio button value you can use checkbox.checked, where checkbox is your DOM object selected by querySelector.
You're basically already doing it. When you click the button, in the click handler for the button, just grab the radio button element using a selector (either class or id), with a "querySelector" call (just like you're doing). Inspect that element for whatever property makes sense (probably "checked").
Something like:
<button onclick="onClick ()">Click Me</button>
...
onClick () {
const kleuren = document.querySelector ( [mySelectorByIDorClass, etc.] );
console.log ( kleuren.checked );
}
See here:
https://www.w3schools.com/jsref/prop_radio_checked.asp
The checked property will tell you whether the element is selected:
if (document.getElementById('id').checked) {
var variable = document.getElementById('id').value;
}

How to check if a <input type="button"> is checked?

The title is self-explanatory, I tried using .checked(and several other methods that also failed), but it did not work.
I want to know how, so I can count the score for a quiz.
Here is the html part for it:
<html>
<head lang=pt>
<meta charset="utf-8">
<title>Formulario</title>
<link rel="stylesheet" type="text/css" href="quiz1.css">
<script src=quiz.js></script>
</head>
<body>
<form class=formulario onsubmit="return mostrar_placar()">
<h3 id = "pergunta">Qual é o nome do inventor da linguagem de programação Python?<br></h3>
<input class = "escolhas" id ="0" type="button" value="Guido van Rossum" onclick="keep_highlighted('0')"><br>
<input class = "escolhas" id ="1" type="button" value="Dennis Ritchie" onclick="return keep_highlighted('1')"><br>
<input class = "escolhas" id ="2" type="button" value="James Gosling" onclick="return keep_highlighted('2')"><br>
<input class = "escolhas" id ="3" type="button" value="Brendan Eich" onclick="return keep_highlighted('3')"><br>
<h3 id = "pergunta">Dentre as alternativas a seguir, qual não é um item de hardware?<br></h3>
<input class = "escolhas" id ="4" type="button" value="Mouse" onclick="return keep_highlighted('4')"><br>
<input class = "escolhas" id ="5" type="button" value="Processador" onclick="return keep_highlighted('5')"><br>
<input class = "escolhas" id ="6" type="button" value="Chipset" onclick="return keep_highlighted('6')"><br>
<input class = "escolhas" id ="7" type="button" value="Debian" onclick="return keep_highlighted('7')"><br><br>
<input type="submit" value="confirmar">
</form>
</body>
</html>
And this is the js:
var certos = ["0", "7"];
function keep_highlighted(id) {
document.getElementById(id).style.background = "white";
document.getElementById(id).style.color = "black";
}
function placar() {
var placar = 0;
for (var i = 0; i < 8; i++) {
console.log(document.getElementById(i.toString()).checked);
if (document.getElementById(i.toString()).checked) {
if (document.getElementById(i.toString()).value == certos[i]) {
placar += 1;
}
}
}
return placar;
}
function mostrar_placar() {
alert("Seu placar é " + placar());
}
The console is only printing 8 falses no matter what I click(showing that its never checked). So it never enters in the condition that counts the score (without if (document.getElementById(i.toString()).checked) it always shows 2 on the score since it loops through all the buttons even the ones not selected). And with it always shows the score as 0....can someone help?
Buttons should not be used to signify an answer unless they are part of a group of choices. Then, you have to decide if only one item from the group should be allowed to be selected or if multiple items are allowable. This is exactly what checkboxes and radio buttons are for.
Now, you don't have to show the user checkboxes or radio buttons - you can show them something that looks like a button instead, but the "buttons" need to behave either like checkboxes or radio buttons. This can be accomplished by actually using checkboxes or radio buttons, but hiding those and, instead, showing label elements that are tied to the hidden items.
Then, in your JavaScript, you can access the actual checkboxes and radio buttons as you normally would.
Here is an example of using hidden checkboxes so that multiple "button" elements can be selected:
document.getElementById("getChecked").addEventListener("click", function(){
// Gather up all the checked checkboxes into an Array;
var checkedCheckboxes =
Array.prototype.slice.call(document.querySelectorAll("input[type='checkbox']:checked"));
// Set up result array
var result = [];
// Loop over them and add selected values to array
checkedCheckboxes.forEach(function(checkbox){
result.push(checkbox.value);
});
// Clear old output and log new results
console.clear();
console.log(result);
});
/* Hide the checkboxes */
input[type='checkbox'] { display:none; }
/* Default styling for labels to make them look like buttons */
input[type='checkbox'] + label {
display:inline-block;
box-shadow:1px 1px grey;
border-radius:3px;
background-color:#e0e0e0;
padding:5px;
font-family:Arial, Helvetica, sans-serif;
cursor:pointer;
}
/* Styling for labels when corresponding checkbox is checked */
input[type='checkbox']:checked + label {
box-shadow:-1px -1px grey;
background-color:#f78d32;
}
<input type="checkbox" id="chk1" name="chk1" value="choice 1">
<label for="chk1">Choice 1</label>
<input type="checkbox" id="chk2" name="chk2" value="choice 2">
<label for="chk2">Choice 2</label>
<input type="checkbox" id="chk3" name="chk3" value="choice 3">
<label for="chk3">Choice 3</label>
<p><button id="getChecked">Get the checked checkbox values</button></p>
Using radio buttons, so that only one "button" can be selected, is almost identical, except for the HTML uses input type=radio and the CSS and JavaScript selectors change to find those radio buttons. Also, since only one radio button can ever be selected (within any given group), there's no need to gather up all the checked radio buttons (from one group) into an array. There will just be one checked button.
document.getElementById("getChecked").addEventListener("click", function(){
// Get the one radio button (within its group) that is checked:
var checkedRadio = document.querySelector("input[type='radio'][name='rad']:checked");
// Clear old output and log new results
console.clear();
console.log(checkedRadio.value);
});
/* Hide the checkboxes */
input[type='radio'] { display:none; }
/* Default styling for labels to make them look like buttons */
input[type='radio'] + label {
display:inline-block;
box-shadow:1px 1px grey;
background-color:#e0e0e0;
padding:5px;
border-radius:3px;
font-family:Arial, Helvetica, sans-serif;
cursor:pointer;
}
/* Styling for labels when corresponding radio button is checked */
input[type='radio']:checked + label {
box-shadow:-1px -1px grey;
background-color:#f78d32;
}
<input type="radio" id="rad1" name="rad" value="choice 1">
<label for="rad1">Choice 1</label>
<input type="radio" id="rad2" name="rad" value="choice 2">
<label for="rad2">Choice 2</label>
<input type="radio" id="rad3" name="rad" value="choice 3">
<label for="rad3">Choice 3</label>
<p><button id="getChecked">Get the checked radio button value</button></p>
"Ah so how I see if it's highlighted..."
It appears that you want to know if the button is highlighted, which basically is to say that it's the element that is "active" or has focus. You can get this via document.activeElement.
Here's a demo that shows the active element change with clicks on the body.
document.body.onclick = function() {
console.log(document.activeElement);
};
html, body { height: 100%; }
<button>button</button>
<input placeholder="click in here">
However, you're asking about your solution instead of fully explaining the problem. I don't know how this relates to scoring a quiz, so it could be that you need something very different.
An input button cannot be "checked" in itself. You have a few options for how to handle this though. You could change the elements to a form with radio buttons or checkbox buttons. However, if you want to keep the buttons you could also do something in the javascript keep_highlighted method when the button is clicked such as:
if (document.getElementById(id).classList.contains("checked")) {
document.getElementById(id).classList.remove("checked");
} else {
document.getElementById(id).classList.add("checked");
}
and you can get this list of "checked" buttons by using:
document.getElementsByClassName("checked");
This will toggle the "checked" class on the element, which you can get a list of elsewhere in your javascript, such as wherever your submit button directs to
EDIT: Also, you could move your button styling into these if blocks so that you could "toggle" the buttons to be highlighted or not based on them being clicked and users could also "uncheck" a selection.
document.getElementById(id).setAttribute("checked","");
document.getElementById(id).removeAttribute("checked");
You want to set a property such as 'checked' or 'clicked' or 'highlighted' for each button. Then when you click the button, set that to true. Then to check which have been clicked, loop those buttons and check if 'clicked' is true or false.
let buttons = document.querySelectorAll('input[type="button"]');
let buttonData = Array.from(buttons).map((el, i) => {
el.addEventListener('click', ()=>{
const clicked = !buttonData[i].clicked;
buttonData[i].clicked = clicked;
if(clicked){
el.classList.add('highlighted');
} else {
el.classList.remove('highlighted');
}
});
return {element: el, clicked:false}
});
buttonData.forEach((btn, i) => {
});
document.getElementById('check-buttons').addEventListener('click', ()=>{
buttonData.forEach((btn, i) => {
console.log("button:", btn.element.id, "is highlighted?", btn.clicked);
});
});
input[type="button"] {
min-width: 100px;
display: block;
}
.highlighted {
background-color: white;
outline: 2px solid rgba(230,200,100);
}
<input type="button" id="button0" value="button 0">
<input type="button" id="button1" value="button 1">
<input type="button" id="button2" value="button 2">
<input type="button" id="button3" value="button 3">
<br>
<button id="check-buttons"> which buttons are highlighted ?</button>

Hiding and showing html elements with radio button and javascript style=none

I am trying to write a function that will show or hide an html element (contained in a div) using javascript. Right now I have 3 radio buttons (to eventually show/hide 3 elements depending on radio button selected, but right now I am just trying to hide one element (month) if year or week is selected, and to show it if month is selected. My html is:
<div id="setting">
<input type="radio" id="year" name="view" value="year"> year<br>
<input type="radio" id="month" name="view" value="month"> month<br>
<input type="radio" id="week" name="view" value="week"> week
</div>
<div id="cal">
(element here I am trying to show/hide)
</div>
My javascript is:
function defineSetting (){
var setting = document.getElementById('setting').checked;
if(setting =='year'){
document.getElementById("cal").style.display = "none";
}else if(setting =='month'){
document.getElementById("cal").style.display = "unset";
}else if(setting =='week'){
document.getElementById("cal").style.display = "none";
}
}
I am also not super experienced with javascript and am trying to figure out how to call the function (if it works). If it is in the document ready function will it run when the page is loaded or do i need to call it somewhere.
I think this is what you're going for. You want to add an event listener to the buttons, and pass the value of the input that's checked to the defineSetting() function that hides/shows your #cal element. I also simplified your test in defineSetting()
<div id="setting">
<input type="radio" id="year" name="view" value="year" class="setting"> year<br>
<input type="radio" id="month" name="view" value="month" class="setting"> month<br>
<input type="radio" id="week" name="view" value="week" class="setting"> week
</div>
<div id="cal">
(element here I am trying to show/hide)
</div>
<style>
.hidden { display: none; }
</style>
<script>
var inputs = document.getElementsByClassName('setting'),
setting;
for (var i = 0; i < inputs.length; i++) {
var el = inputs[i];
el.addEventListener('change', function() {
defineSetting(this.value);
})
}
function defineSetting(setting) {
if (setting == 'year' || setting == 'week') {
document.getElementById("cal").classList.add('hidden');
} else {
document.getElementById("cal").classList.remove('hidden');
}
}
</script>
This will help you out:
How to get value of selected radio button?
You are trying to get the checked value of a div element, but this element doesn't have that. The input element do have that property so that's where you can get it from.

Javascript radio display none/inline

In my HTML code I have this two inputs:
Yes <input type="radio" onclick="RadioCheck()" name="radio" id="yes" />
No <input type="radio" onclick="RadioCheck()" name="radio" id="no" />
Now I have a div that is by default as it's style display inline, and I want that when I click no it makes it style display none and yes will make it inline, so I made this function
function RadioCheck() {
var Radioclick = document.getElementById("hiddendiv").style.display;
if (Radioclick == "inline") {
document.getElementById("hiddendiv").style.display = "none";
}
if (Radioclick == "none") {
document.getElementById("hiddendiv").style.display = "inline";
}
}
Now the problem is that I don't know how to do it that when I click yes it will switch to inline and if I click yes again it will stay inline instead of switching it to none, I know my code just switch between inline to none but I want it to make it inline when yes radio is clicked and none when no radio is clicked without two functions.
Perhaps you could pass a variable to the RadioCheck() function?
Yes <input type="radio" onclick="RadioCheck(true)" name="radio" id="yes" />
No <input type="radio" onclick="RadioCheck(false)" name="radio" id="no" />
And then in your javascript:
function RadioCheck(isYes){
if(isYes){
document.getElementById("hiddendiv").style.display = "inline";
}else{
document.getElementById("hiddendiv").style.display = "none";
}
}
If you want the div's display to be determined by the radio button checked, the condition should be on the radio checked:
if the Yes radio button is checked
show the div
if the No radio button is checked
hide the div
So:
if (document.getElementById("yes").checked) {
document.getElementById("hiddendiv").style.display = "inline";
}
if (document.getElementById("no").checked) {
document.getElementById("hiddendiv").style.display = "none";
}
See http://jsfiddle.net/nivas/39cMn/ for an working example
If you add a value attribute to your radio buttons and pass the radio button id to the function RadioCheck you can use the button value to simplify the code. For example:
<form>
Yes <input type="radio" onclick="RadioCheck('yes')" name="radio" id="yes" value="inline" />
No <input type="radio" onclick="RadioCheck('no')" name="radio" id="no" value="none" />
</form>
<div id="hiddendiv" style="display:none">
this div can be hidden and revealed
</div>
<script>
function RadioCheck(id) {
var value = document.getElementById(id).value;
document.getElementById("hiddendiv").style.display = value;
}
</script>

Categories