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>
Related
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>
let tile = document.getElementById("tile")
//see if a button is checked by creating a loop to iterate through the radio buttons
for (let i = 0; i < document.forms.choice.length; i++) {
if (document.forms.choice[i].checked ) { //form.choice = returns an array of the radio buttons
//checked returns a boolean if the button is checked or not; ask if the button is clicked or not and if it is follow this new loop
for (let i = 0; i < document.forms.choice.length; i++) { //this new loop iterates and asks if the value is a certain color, and if it is change the background color
if (document.forms.choice[i].value === "blue") {
tile.style.backgroundColor = 'blue';
} else if (document.forms.choice[i].value === "erase") {
tile.style.backgroundColor = 'white';
}
}
}
}
So I'm trying to get the tile to change colors when it is hovered on depending on which option is selected. (For the example right now it's just set to change the background color for simplicity purposes although I still haven't figured out to do it onhover). So what I tried to do was iterate over the form group to see if anything is checked or not, and then if it is move on to a nested loop which asks if the value is a certain color. I feel like i have the logic down right, but nothing activates and I'm not sure what else i can do. But obviously there's a mistake I'm just not catching.
<form id="color-options" name="form">
<input type="radio" name="choice" value="blue">
<label for="blue">Blue</label>
<input type="radio" name="choice" value="">
<label for="rainbow">Rainbow</label>
<input type="radio" name="choice" value="white">
<label for="erase">Eraser</label>
<input type="radio" name="choice" value="user">
<label for="color-picker">Color Picker</label>
<input type="color" id="color-picker">
</form>
<div id="Sketch">
<div id="tile">
</div>
</div>
JSfiddle: https://jsfiddle.net/Jbautista1056/83scu1ra/2/
I have multiple radio buttons, each one inside a <span> with margin, so they seem like a button with a radio element inside. how can I check the radio button when I click anywhere inside the <span> parent element of the radio button
UX oriented
<span class="radio-box" id="white-box">
<input type="radio" id="white" name="colour"> White
</span>
<span class="radio-box" id="red-box">
<input type="radio" id="red" name="colour"> Red
</span>
<span class="radio-box" id="blue-box">
<input type="radio" id="blue" name="colour"> Blue
</span>
sorry, very noob at Javascript
thanks :)
This is exactly what label elements are for. Use those, rather than span elements:
<label class="radio-box" id="white-box">
<input type="radio" id="white" name="colour"> White
</label>
<label class="radio-box" id="red-box">
<input type="radio" id="red" name="colour"> Red
</label>
<label class="radio-box" id="blue-box">
<input type="radio" id="blue" name="colour"> Blue
</label>
When the label wraps the input like that, it's associated with that input. (If you couldn't use wrapping, you could use the for attribute to tell the label what the id of its associated input is.)
You could make it work with spans. Targeting just those spans:
$("span > input[type=radio][name=colour]").parent().on("click", function() {
$(this).find("input[type=radio][name=colour]").prop("checked", true);
});
or targeting any input[type=radio] inside a span.radio-box:
$("span.radio-box > input[type=radio]").parent().on("click", function() {
$(this).find("input[type=radio]").prop("checked", true);
});
But again, this is exactly what label is for, so best to use that.
If you want to do this without the <label> tag and without jquery and just vanilla JavaScript then here's a solution.
var radioBoxes = document.querySelectorAll("span.radio-box");
radioBoxes.forEach(function (box) {
var radioButton = box.querySelector("input[type='radio']");
box.addEventListener("click", function () {
radioButton.click();
});
});
I have a radio button like this on page
<div id="someId">
<label class="radio-inline">
<input name="x" type="radio" onchange="GetSelectedVal();">Yes</label>
<label class="radio-inline">
<input name="x" type="radio" onchange="GetSelectedVal();">No</label>
</div>
On page load I don't want to set any selection so not using checked property. In my JavaScript function, how can I get the value Yes or No based on the user selection at runtime?
function GetSelectedVal() {
console.log($('#someId input:radio.........);
}
I have seen similar questions but unable to find solution of this issue.
Remove onchange inline handler from HTML. Use on to bind events.
:checked will select the checked radio button. closest will select the parent label and text() will get the label associated with the radio button. e.g. Yes
$('[name="x"]').on('change', function () {
alert($('[name="x"]:checked').closest('label').text());
});
DEMO
You can simple pass this in onchange="GetSelectedVal(); like onchange="GetSelectedVal(this);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="someId">
<label class="radio-inline"><input name="x" type="radio" onchange="GetSelectedVal(this);">Yes</label>
<label class="radio-inline"><input name="x" type="radio" onchange="GetSelectedVal(this);">No</label>
</div>
<script>
function GetSelectedVal(ele) {
alert($(ele).closest('label').text());
}
</script>
I would do it a bit different than the accepted answer.
Instead of having events on multiple radio buttons, you can have one on the containing div. Also let just the checked radio trigger the change:
$('#someId').on('change', 'input[name="x"]:checked', function () {
var label = $(this).siblings('span').text();
console.log(label);
});
When I have text next to other elements I prefer wrapping the text in span's:
<div id="someId">
<label class="radio-inline"><input name="x" type="radio"><span>Yes</span></label>
<label class="radio-inline"><input name="x" type="radio"><span>No</span></label>
</div>
A demo: jsfiddle.net/qcxgwe66/
I want to make radio buttons disappear and instead of buttons, the label of the radio buttons will be clickable itself and i will change the background color of the selected radio. How can i do this? For example, I have "yes" and "no" labels and these labels will be clickable and there will be no radio buttons at all. These are only changing color of background but showing radio buttons which is not wanted.
Javascript
$(document).ready(function(){
var ok = "green";
var notok = "red";
$.each($(":radio"), function(){
if($(this).prop("checked") == false)
{
$(this).parent().css("background", notok);
}
else
{
$(this).parent().css("background", ok );
}
})
$(":radio").click(function(){
$("[name='"+$(this).prop("name")+"']").parent().css("background", notok);
$(this).parent().css("background", ok );
})
})
HTML
<FORM name="form1">
<div>
<input type="radio" id="yes" name="q"checked="checked"/> Yes
</div>
<div>
<input type="radio" id="no" name="q"/>No
</div>
</FORM>
Thanks
This one is actually deceptively easy. If you just use a "label" tag, it will be clickable. Then you can simply hide the radio button.
<input id="yes" type="radio" name="q" value="radiobutton" style="display:none;" />
<label for="yes">Yes </label>
<input id="no" type="radio" name="q" value="radiobutton" style="display:none;" />
<label for="no">No</label>
btw, here's a JSFiddle of it working: http://jsfiddle.net/scGE9/2/
If I understand what you're asking, I'd hide the radio buttons, then attach a click handler to the labels that changed the background color:
$('label').click(function () {
$('label').removeClass('selected');
$(this).addClass('selected');
});
Here's a jsfiddle to demonstrate.
In short, when a label is clicked, remove the 'selected' class controlling the background color from all relevant labels, and apply it to the one that was clicked.