I know this has been asked a few times but I haven't seen any posts regarding the use of the labels. The code below works for deselecting a radio button when no labels are written.
How can I add labels which allow the radio buttons to be selected/deselected with the clicking of the words rather than just the radio button itself. When I add labels my code seems to go haywire.
This is the working snippet with spans instead of labels
document.getElementsByName('foo').forEach((radioBttn) => {
radioBttn.addEventListener('click', function first() {
if (this.checked) {
this.onclick = function second() {
this.checked = false;
};
} else {
this.onclick = null;
}
});
});
document.getElementsByName('bar').forEach((radioBttn) => {
radioBttn.addEventListener('click', function first() {
if (this.checked) {
this.onclick = function second() {
this.checked = false;
};
} else {
this.onclick = null;
}
});
});
<span class="foo">
<input type="radio" name="foo"> Foo</span>
<span class="bar">
<input type="radio" name="bar"> Bar</span>
<br>
<span class="foo">
<input type="radio" name="foo"> Foo</span>
<span class="bar">
<input type="radio" name="bar"> Bar</span>
<br>
<span class="foo">
<input type="radio" name="foo"> Foo</span>
<span class="bar">
<input type="radio" name="bar"> Bar</span>
This is the non-working snippet with labels instead of spans
document.getElementsByName('foo').forEach((radioBttn) => {
radioBttn.addEventListener('mousedown', function first() {
if (this.checked) {
this.onclick = function second() {
this.checked = false;
};
} else {
this.onclick = null;
}
});
});
document.getElementsByName('bar').forEach((radioBttn) => {
radioBttn.addEventListener('mousedown', function first() {
if (this.checked) {
this.onclick = function second() {
this.checked = false;
};
} else {
this.onclick = null;
}
});
});
<label class="foo" for="foo1">
<input type="radio" name="foo" id="foo1">Foo</label>
<label class="bar" for="bar1">
<input type="radio" name="bar" id="bar1">Bar</label>
<br>
<label class="foo" for="foo2">
<input type="radio" name="foo" id="foo2">Foo</label>
<label class="bar" for="bar2">
<input type="radio" name="bar" id="bar2">Bar</label>
<br>
<label class="foo" for="foo3">
<input type="radio" name="foo" id="foo3">Foo</label>
<label class="bar" for="bar3">
<input type="radio" name="bar" id="bar3">Bar</label>
Related
I want to make the parent label element bold on a radio / checkbox check. It's working for checkboxes, but the radio's label stays bold.
HTML:
<h4>Radios:</h4>
<div class="checkgroup">
<label for="green"><input type="radio" name="test" id="green">Green</label>
<label for="blue"><input type="radio" name="test" id="blue">Blue</label>
<label for="red"><input type="radio" name="test" id="red">Red</label>
</div>
<hr />
<h4>Checkboxes:</h4>
<div class="checkgroup">
<label for="green-check"><input type="checkbox" id="green-check">Green</label>
<label for="blue-check"><input type="checkbox" id="blue-check">Blue</label>
<label for="red-check"><input type="checkbox" id="red-check">Red</label>
</div>
JavaScript:
function makeLabelBold() {
const radios = document.querySelectorAll("input[type='radio']");
const checkboxes = document.querySelectorAll("input[type='checkbox']");
radios.forEach((radio) => {
radio.addEventListener("click", function () {
this.checked
? (this.parentElement.style.fontWeight = "700")
: (this.parentElement.style.fontWeight = "400");
});
});
checkboxes.forEach((checkbox) => {
checkbox.addEventListener("click", function () {
this.checked
? (this.parentElement.style.fontWeight = "700")
: (this.parentElement.style.fontWeight = "400");
});
});
}
makeLabelBold();
I tried using a change event instead of a click, but that didn't work. Any ideas? Here's a Pen to try out.
Codepen:
Codepen for testing
You can do this without JavaScript. You can use :checked CSS selector. Something like this:
input:checked + span {
font-weight: 700;
}
<h4>Radios:</h4>
<div class="checkgroup">
<label for="green"><input type="radio" name="test" id="green"><span>Green</span></label>
<label for="blue"><input type="radio" name="test" id="blue"><span>Blue</span></label>
<label for="red"><input type="radio" name="test" id="red"><span>Red</span></label>
</div>
<hr />
<h4>Checkboxes:</h4>
<div class="checkgroup">
<label for="green-check"><input type="checkbox" id="green-check"><span>Green</span></label>
<label for="blue-check"><input type="checkbox" id="blue-check"><span>Blue</span></label>
<label for="red-check"><input type="checkbox" id="red-check"><span>Red</span></label>
</div>
If you would like to use JavaScript anyway:
Radio lists doesn't fire event for each of its radio box but only for the one which has been really changed (which you have clicked / as long as we are not changing its value programmaticaly). What I did:
replaced this with e.target to get radio which you have clicked.
get it's name attribute with getAttribute("name")
find all radios with same name attribute`
remove style from all radios with this attribute
apply style on currently selected radio
function makeLabelBold() {
const radios = document.querySelectorAll("input[type='radio']");
const checkboxes = document.querySelectorAll("input[type='checkbox']");
radios.forEach((radio) => {
radio.addEventListener("click", function (e) {
const inputsName = e.target.getAttribute("name");
const sameNameRadios = document.querySelectorAll("[name='"+inputsName+"']");
sameNameRadios.forEach(radio=>{
radio.parentElement.style.fontWeight = "400";
});
e.target.parentElement.style.fontWeight = "700";
});
});
checkboxes.forEach((checkbox) => {
checkbox.addEventListener("click", function () {
this.checked
? (this.parentElement.style.fontWeight = "700")
: (this.parentElement.style.fontWeight = "400");
});
});
}
makeLabelBold();
<h4>Radios:</h4>
<div class="checkgroup">
<label for="green"><input type="radio" name="test" id="green">Green</label>
<label for="blue"><input type="radio" name="test" id="blue">Blue</label>
<label for="red"><input type="radio" name="test" id="red">Red</label>
</div>
<hr />
<h4>Checkboxes:</h4>
<div class="checkgroup">
<label for="green-check"><input type="checkbox" id="green-check">Green</label>
<label for="blue-check"><input type="checkbox" id="blue-check">Blue</label>
<label for="red-check"><input type="checkbox" id="red-check">Red</label>
</div>
Without changing the HTML:
(function()
{
const
radios = document.querySelectorAll('input[type="radio"]')
, checkboxes = document.querySelectorAll('input[type="checkbox"]')
;
radios.forEach(radio =>
{
radio.onclick = () =>
radios.forEach( r =>
r.closest('label').style.fontWeight = r.checked ? '700' : '400' )
});
checkboxes.forEach(checkbox =>
{
checkbox.onclick = () =>
checkbox.closest('label').style.fontWeight = checkbox.checked ? '700' : '400'
});
}
)()
<h4>Radios:</h4>
<div class="checkgroup">
<label for="green"><input type="radio" name="test" id="green">Green</label>
<label for="blue"><input type="radio" name="test" id="blue">Blue</label>
<label for="red"><input type="radio" name="test" id="red">Red</label>
</div>
<hr />
<h4>Checkboxes:</h4>
<div class="checkgroup">
<label for="green-check"> <input type="checkbox" id="green-check">Green</label>
<label for="blue-check"> <input type="checkbox" id="blue-check" >Blue </label>
<label for="red-check"> <input type="checkbox" id="red-check" >Red </label>
</div>
you can olso do:
(function()
{
const radios_checkboxes = document.querySelectorAll('input[type="radio"], input[type="checkbox"]');
radios_checkboxes.forEach(rc =>
{
rc.onclick =()=>
radios_checkboxes.forEach(elm =>
elm.closest('label').style.fontWeight = elm.checked ? '700' : '400' )
});
}
)();
i need to check if checkbox 1 or 2 is clicked.
error : only background is printing while clicking any checbox and pressing button
function onlyOne(checkbox) {
var checkboxes = document.getElementsByName('check')
checkboxes.forEach((item) => {
if (item !== checkbox) item.checked = false;
});
}
function run() {
var checkboxes = document.getElementsByName('check')
if (document.getElementById('c1').checked) {
alert("background");
} else if (document.getElementById('c1').checked) {
alert("foreground");
}
}
<input type="checkbox" name="check" id="c1" value="background" onclick="onlyOne(this)">background</input>
<input type="checkbox" name="check" id="c2" value="foreground" onclick="onlyOne(this)">foreground</input>
<input type="button" value="button" onclick="run()">
In the second statment you write c1 again instead of c2
function onlyOne(checkbox) {
var checkboxes = document.getElementsByName('check')
checkboxes.forEach((item) => {
if (item !== checkbox) item.checked = false;
});
}
function run() {
var checkboxes = document.getElementsByName('check')
if (document.getElementById('c1').checked) {
alert("background");
} else if (document.getElementById('c2').checked) {
alert("foreground");
}
}
<input type="checkbox" name="check" id="c1" value="background" onclick="onlyOne(this)">background</input>
<input type="checkbox" name="check" id="c2" value="foreground" onclick="onlyOne(this)">foreground</input>
<input type="button" value="button" onclick="run()">
Instead of use your method why don't use radio and print the radio checked like:
document.getElementById('run').addEventListener('click',AlertMe);
function AlertMe() {
document.getElementsByName('check').forEach( (el) =>{
if(el.checked === true) alert(el.value);
});
}
<input type="radio" name="check" value="background">background</input>
<input type="radio" name="check" value="foreground">foreground</input>
<input type="button" value="button" id='run'>
It's miss named ID of element for foreground
function run(){
[...]
else if(document.getElementById('c1').checked){
alert("foreground");
[...]
it should be:
[...]
else if(document.getElementById('c2').checked){
alert("foreground");
[...]
I'm trying to make it so, when you checked/uncheck a checkbox, the img appears/disappears. As of now, when I checked a box, all 4 of the images appear instead of just the one. Also I was wondering is it wrong to use document.ready multiple times? This is what I have:
Js:
$(document).ready
(
function()
{
$("#pump").hide();
$("input:checkbox").change(function() {
this.checked?$("#pump").show():$("#pump").hide();
});
});
$(document).ready
(
function()
{
$("#ski").hide();
$("input:checkbox").change(function() {
this.checked?$("#ski").show():$("#ski").hide();
});
});
$(document).ready
(
function()
{
$("#ship").hide();
$("input:checkbox").change(function() {
this.checked?$("#ship").show():$("#ship").hide();
});
});
$(document).ready
(
function()
{
$("#sun").hide();
$("input:checkbox").change(function(){
this.checked?$("#sun").show():$("#sun").hide();
});
});
Html:
<div>
<input type="checkbox"></input>
<label> Pumpkins </label>
<img src="images/pumpkins.jpg" id="pump">
<input type="checkbox"></input>
<label> Ski Resort </label>
<img src="images/ski resort.jpg" id="ski">
<input type="checkbox"></input>
<label> Bahamas </label>
<img src="images/bahamas.jpg" id="sun">
<input type="checkbox"></input>
<label> Cruise </label>
<img src="images/cruise.jpg" id="ship">
</div>
$(window).on("load", function() {
$("#pump").hide();
$("#ski").hide();
$("#sun").hide();
$("#ship").hide();
});
$("#id1").change(function() {
if(this.checked) {
$("#pump").show();
}
else{
$("#pump").hide();
}
});
$("#id2").change(function() {
if(this.checked) {
$("#ski").show();
}
else{
$("#ski").hide();
}
});
$("#id3").change(function() {
if(this.checked) {
$("#sun").show();
}
else{
$("#sun").hide();
}
});
$("#id4").change(function() {
if(this.checked) {
$("#ship").show();
}
else{
$("#ship").hide();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id = "id1" type="checkbox"></input>
<label> Pumpkins </label>
<img src="images/pumpkins.jpg" id="pump">
<input id = "id2" type="checkbox"></input>
<label> Ski Resort </label>
<img src="images/ski resort.jpg" id="ski">
<input id = "id3" type="checkbox"></input>
<label> Bahamas </label>
<img src="images/bahamas.jpg" id="sun">
<input id = "id4" type="checkbox"></input>
<label> Cruise </label>
<img src="images/cruise.jpg" id="ship">
You need to create ids for your checkboxes.
And within your event listener for the checkbox, you have to check whether the box has been selected or not. I like tu use IF ELSE.
I have to add the class 'revealed' to a div, once the radio button with the label 'yes' has been selected. So far I have my code set up so that I apply a 'required' class to the input that will be revealed, but I need to have a way to add the class 'revealed' to the 'reveal-if-active' div. This entire HTML structure will repeat as there will be multiple yes/no questions after this first one. So each 'reveal-if-active' div must be unique.
Here's the HTML structure that I am required to use:
<div class="form-group two-column">
<input id="a1" type="radio" name="ayesno" value="1">
<label for="a1">yes</label>
</div>
<div class="form-group two-column">
<input id="a2" type="radio" name="ayesno" value="2">
<label for="a2">no</label>
</div>
<div class="reveal-if-active">
<label for="how-many-people">If <strong>yes</strong> how many people?</label>
<input type="text" name="a-how-many-people" class="require-if-active" data-require-pair="#a1" required="">
</div>
Here's the JS I have so far:
var FormStuff = {
init: function() {
this.applyConditionalRequired();
this.bindUIActions();
},
bindUIActions: function() {
$("input[type='radio'], input[type='checkbox']").on("change", this.applyConditionalRequired);
},
applyConditionalRequired: function() {
$(".require-if-active").each(function() {
var el = $(this);
if ($(el.data("require-pair")).is(":checked")) {
el.prop("required", true);
$('[data-id=' + $('input:checked').prop('id') + ']').addClass('reveal');
} else {
el.prop("required", false);
el.removeClass("revealed");
}
});
}
};
FormStuff.init();
You may use el.closest('div.reveal-if-active'):
var FormStuff = {
init: function () {
this.applyConditionalRequired();
this.bindUIActions();
},
bindUIActions: function () {
$("input[type='radio'], input[type='checkbox']").on("change", this.applyConditionalRequired);
},
applyConditionalRequired: function () {
$(".require-if-active").each(function () {
var el = $(this);
if ($(el.data("require-pair")).is(":checked")) {
el.prop("required", true);
el.closest('div.reveal-if-active').addClass("revealed");
} else {
el.prop("required", false);
el.closest('div.reveal-if-active').removeClass("revealed");
}
});
}
};
$(function () {
FormStuff.init();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group two-column">
<input id="a1" type="radio" name="ayesno" value="1">
<label for="a1">yes</label>
</div>
<div class="form-group two-column">
<input id="a2" type="radio" name="ayesno" value="2">
<label for="a2">no</label>
</div>
<div class="reveal-if-active">
<label for="i1">If <strong>yes</strong> how many people?</label>
<input id="i1" type="text" name="a-how-many-people" class="require-if-active" data-require-pair="#a1" required="">
</div>
In Area 1, when I checked checkbox bbbbbb or checkbox cccccc
input will disable , it's not work
But in Area 2 it's OK
Why Area1 function not work ?
thank you.
Area 1
<br>
<input type="text" id="a" name="a">
<br>
<input type="checkbox" id="b" name="b"/> bbbbbb
<br>
<input type="checkbox" id="c" name="c"/> cccccc
</div>
<script type="text/javascript">
window.onload=function(){
document.getElementById('b').onchange = function () {
document.getElementById('c').checked = false;
document.getElementById('a').disabled = this.checked;
};
document.getElementById('c').onchange = function () {
document.getElementById('b').checked = false;
document.getElementById('a').disabled = this.checked;
};
}
</script>
<br>
<br>
<br>
<br>
<br>
Area 2
<br>
<input type="text" id="1" name="1">
<br>
<input type="checkbox" id="2" name="2"/> 222222
<br>
<input type="checkbox" id="3" name="3"/> 333333
</div>
<script type="text/javascript">
window.onload=function(){
document.getElementById('2').onchange = function () {
document.getElementById('3').checked = false;
document.getElementById('1').disabled = this.checked;
};
document.getElementById('3').onchange = function () {
document.getElementById('2').checked = false;
document.getElementById('1').disabled = this.checked;
};
}
</script>
The second window.onload is overriding the first one.
Why Area1 function not work ?
Because you are overwriting window.onload with a new function. Only the function that you assigned last will be executed on page load.
That's one of the reasons why to use addEventListener to bind event handlers:
window.addEventListener('load', function() {
// ..
});
This allows you to bind multiple handlers to the same element.
There are a couple of alternatives:
Aggregate both functions into one.
Create the functions explicitly and call both in the event handler. E.g.
function area1() { ... }
function area2() { ... }
window.onload = function() {
area1();
area2();
};
Don't use window.onload at all. Since you already placed the code after the elements in the document, you don't need window.onload. You can run the code directly, e.g.
Area 1
<br>
<input type="text" id="a" name="a">
<br>
<input type="checkbox" id="b" name="b"/> bbbbbb
<br>
<input type="checkbox" id="c" name="c"/> cccccc
</div>
<script type="text/javascript">
document.getElementById('b').onchange = function () {
document.getElementById('c').checked = false;
document.getElementById('a').disabled = this.checked;
};
document.getElementById('c').onchange = function () {
document.getElementById('b').checked = false;
document.getElementById('a').disabled = this.checked;
};
</script>
I recommend to read the excellent articles about event handling on quirksmode.org. The explain all the different ways of how to bind event handlers.
You can't have the window.onload=function(){ function twice, it can only be declared once. If you declare it twice, it will choose one of them to work when the window is loaded. Use this instead:
Area 1
<br>
<input type="text" id="a" name="a">
<br>
<input type="checkbox" id="b" name="b"/> bbbbbb
<br>
<input type="checkbox" id="c" name="c"/> cccccc
</div>
<br>
<br>
<br>
<br>
<br>
Area 2
<br>
<input type="text" id="1" name="1">
<br>
<input type="checkbox" id="2" name="2"/> 222222
<br>
<input type="checkbox" id="3" name="3"/> 333333
<script type="text/javascript">
window.onload=function(){
document.getElementById('b').onchange = function () {
document.getElementById('c').checked = false;
document.getElementById('a').disabled = this.checked;
};
document.getElementById('c').onchange = function () {
document.getElementById('b').checked = false;
document.getElementById('a').disabled = this.checked;
};
document.getElementById('2').onchange = function () {
document.getElementById('3').checked = false;
document.getElementById('1').disabled = this.checked;
};
document.getElementById('3').onchange = function () {
document.getElementById('2').checked = false;
document.getElementById('1').disabled = this.checked;
};
}
</script>