On Change Event on working in jQuery - javascript

When I click on the single checkbox, it changes and green colored. But when I check Full day, all checkboxes are checked but color not change. also after checking full Day, I uncheck all times still full day is checked. I'm stuck, what wrong with this code?
$(document).ready(function() {
$('input:checkbox[name="time"]').change(function() {
$('input:checkbox[name="time"]:not(:checked)').parent().removeClass("active");
$('input:checkbox[name="time"]:checked').parent().addClass("active");
});
});
function selectAll(source) {
checkboxes = document.getElementsByName('time');
for (var i in checkboxes)
checkboxes[i].checked = source.checked;
}
.timing {
width: 500px;
}
.timing label {
width: 100px;
display: inline-block;
border: 1px solid #ccc;
padding: 10px;
text-align: center;
cursor: pointer;
}
.timing label input {
display: block;
}
.timing label.active {
background-color: rgba(0, 204, 0, 1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="timing">
<label for="11:30"><input name="time" class="timess" value="11:30" id="11:30" type="checkbox">11:30</label>
<label for="12:00"><input name="time" class="timess" value="12:00" id="12:00" type="checkbox">12:00</label>
<label for="12:30" class=""><input name="time" class="timess" value="12:30" id="12:30" type="checkbox">12:30</label>
</div>
<label for="selectall"><input type="checkbox" id="selectall" onClick="selectAll(this)" />Full Day</label>
<script>
function selectAll(source) {
checkboxes = document.getElementsByName('time');
for (var i in checkboxes)
checkboxes[i].checked = source.checked;
}
</script>

The issue is because you need to trigger a change event on the checkboxes when clicking the 'Select All' option so that their own event handler runs and changes their background colour. This does not occur when setting the checked state manually, so you can use the trigger() method in your code.
You should note though, that you can improve your logic by using toggleClass() and also removing the on* event attribute as they are outdated. Use an unobtrusive event handler as you do for the normal checkboxes. Try this:
$('input:checkbox[name="time"]').change(function() {
$(this).closest('label').toggleClass('active', this.checked);
});
$('#selectall').change(function() {
$('input:checkbox[name="time"]').prop('checked', this.checked).trigger('change');
});
.timing {
width: 500px;
}
.timing label {
width: 100px;
display: inline-block;
border: 1px solid #ccc;
padding: 10px;
text-align: center;
cursor: pointer;
}
.timing label input {
display: block;
}
.timing label.active {
background-color: rgba(0, 204, 0, 1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="timing">
<label for="11:30">
<input name="time" class="timess" value="11:30" id="11:30" type="checkbox">
11:30
</label>
<label for="12:00">
<input name="time" class="timess" value="12:00" id="12:00" type="checkbox">
12:00
</label>
<label for="12:30">
<input name="time" class="timess" value="12:30" id="12:30" type="checkbox">
12:30
</label>
</div>
<label for="selectall">
<input type="checkbox" id="selectall" />
Full Day
</label>

I added trigger event. Change event will not get fired if you check checkbox using JS.
function selectAll(source) {
checkboxes = document.getElementsByName('time');
for(var i in checkboxes)
checkboxes[i].checked = source.checked;
$('input:checkbox[name="time"]').trigger('change');//Trigger change event to checkbox
}
$(document).ready(function () {
$('input:checkbox[name="time"]').change(function () {
$('input:checkbox[name="time"]:not(:checked)').parent().removeClass("active");
$('input:checkbox[name="time"]:checked').parent().addClass("active");
});
});
function selectAll(source) {
checkboxes = document.getElementsByName('time');
for(var i in checkboxes)
checkboxes[i].checked = source.checked;
$('input:checkbox[name="time"]').trigger('change')
}
.timing{width:500px;}
.timing label{width:100px;display:inline-block;border:1px solid #ccc;padding:10px;text-align:center;cursor:pointer;}
.timing label input{display:block;}
.timing label.active{background-color:rgba(0,204,0,1);}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="timing">
<label for="11:30"><input name="time" class="timess" value="11:30" id="11:30" type="checkbox">11:30</label>
<label for="12:00"><input name="time" class="timess" value="12:00" id="12:00" type="checkbox">12:00</label>
<label for="12:30" class=""><input name="time" class="timess" value="12:30" id="12:30" type="checkbox">12:30</label>
</div>
<label for="selectall"><input type="checkbox" id="selectall" onClick="selectAll(this)" />Full Day</label>
<script>
function selectAll(source) {
checkboxes = document.getElementsByName('time');
for(var i in checkboxes)
checkboxes[i].checked = source.checked;
}
</script>

You need to trigger the change function inside the loop
$(document).ready(function() {
$('input:checkbox[name="time"]').change(function() {
$('input:checkbox[name="time"]').parent().removeClass("active");
$('input:checkbox[name="time"]:checked').parent().addClass("active");
});
});
function selectAll(source) {
checkboxes = document.getElementsByName('time');
for (var i in checkboxes){
checkboxes[i].checked = source.checked;
$('input:checkbox[name="time"]').trigger('change')
}
}
.timing {
width: 500px;
}
.timing label {
width: 100px;
display: inline-block;
border: 1px solid #ccc;
padding: 10px;
text-align: center;
cursor: pointer;
}
.timing label input {
display: block;
}
.timing label.active {
background-color: rgba(0, 204, 0, 1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="timing">
<label for="11:30"><input name="time" class="timess" value="11:30" id="11:30" type="checkbox">11:30</label>
<label for="12:00"><input name="time" class="timess" value="12:00" id="12:00" type="checkbox">12:00</label>
<label for="12:30" class=""><input name="time" class="timess" value="12:30" id="12:30" type="checkbox">12:30</label>
</div>
<label for="selectall"><input type="checkbox" id="selectall" onClick="selectAll(this)" />Full Day</label>

Related

Use only one checkbox from two

I have a form that has two checkboxes, now you can click the checkbox on both
The question is, is it possible to make it so that there is only one choice? For example, clicked on the first one, it turned on, clicked on the second one, the first turned off, the second turned on. It should also be possible to uncheck the box at any time. I know that I can use the radio type, but I need only checkboxes
.call-form-item {
padding-bottom: 12px;
margin-bottom: 24px;
margin-left: 50px;
margin-right: 50px;
}
input {
margin: 0;
box-sizing: border-box;
outline: none;
border: none;
background-color: #EEF0F7;
margin-right: 10px;
}
.input-wrapper {
display: flex;
align-items: flex-start;
}
label {
color: #808694;
font-family: Montserrat;
font-size: 10px;
font-weight: bold;
letter-spacing: 0;
line-height: 16px;
text-transform: uppercase;
margin-right: 10px;
}
input[type=checkbox]:focus {
outline: rgba(0, 0, 0, 0.2);
}
input[type=checkbox] {
background-color: #EEF0F7;
border-radius: 2px;
appearance: none;
-webkit-appearance: none;
-moz-appearance: none;
width: 17px;
height: 17px;
cursor: pointer;
position: relative;
}
input[type=checkbox]:checked {
background-color: #808694;
background: #808694 url("data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==") 3px 3px no-repeat;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="contacts-call-form">
<form class="js-form" action="{{ route('send-contacts-call') }}">
<div class="col-md-6">
<div class="call-form-item">
<label for="name">Name *</label>
<div class="input-wrapper">
<input class="js-form-call-name" id="name" type="text" name="name">
</div>
</div>
</div>
<div class="col-md-6">
<div class="call-form-item">
<label for="email">Email *</label>
<div class="input-wrapper">
<input class="js-form-call-email" id="email" type="email" name="email">
</div>
</div>
</div>
<div class="col-md-6">
<div class="call-form-item">
<div class="input-wrapper">
<input class="js-form-call-check1" id="check1" name="check1" type="checkbox"><label>Check 1</label>
<input class="js-form-call-check2" id="check2" name="check2" type="checkbox"><label>Check 2</label>
</div>
</div>
</div>
</form>
</div>
The script would loo something like this. I didn't test this so there might be misspellings causing errors and such.
// get first checkbox element
let box1 = document.getElementByID( "check1" );
// get second checkbox element
let box2 = document.getElementByID( "check2" );
// add events that fires when boxes are checked
box1.addEventListener( "change", function() {
// see if the other box is already checked
if ( box2.checked ) {
// if so, uncheck it
box2.checked = false;
}
});
box2.addEventListener( "change", function() {
if ( box1.checked ) {
box1.checked = false;
}
});
But you can also just use radio buttons and invoke a hidden reset button when you click a checked radio button I think.
Here is another version that will work with any number of checkboxes.
const inps=document.querySelectorAll(".input-wrapper input");
inps.forEach(e=>e.addEventListener("click",ev=>{
inps.forEach(c=>{if(c!==e) c.checked=false})
}))
.call-form-item {
padding-bottom: 12px;
margin-bottom: 24px;
margin-left: 50px;
margin-right: 50px;
}
input {
margin: 0;
box-sizing: border-box;
outline: none;
border: none;
background-color: #EEF0F7;
margin-right: 10px;
}
.input-wrapper {
display: flex;
align-items: flex-start;
}
label {
color: #808694;
font-family: Montserrat;
font-size: 10px;
font-weight: bold;
letter-spacing: 0;
line-height: 16px;
text-transform: uppercase;
margin-right: 10px;
}
input[type=checkbox]:focus {
outline: rgba(0, 0, 0, 0.2);
}
input[type=checkbox] {
background-color: #EEF0F7;
border-radius: 2px;
appearance: none;
-webkit-appearance: none;
-moz-appearance: none;
width: 17px;
height: 17px;
cursor: pointer;
position: relative;
}
input[type=checkbox]:checked {
background-color: #808694;
background: #808694 url("data:image/gif;base64,R0lGODlhCwAKAIABAP////3cnSH5BAEKAAEALAAAAAALAAoAAAIUjH+AC73WHIsw0UCjglraO20PNhYAOw==") 3px 3px no-repeat;
}
<div class="contacts-call-form">
<form class="js-form" action="{{ route('send-contacts-call') }}">
<div class="col-md-6">
<div class="call-form-item">
<label for="name">Name *</label>
<div class="input-wrapper">
<input class="js-form-call-name" id="name" type="text" name="name">
</div>
</div>
</div>
<div class="col-md-6">
<div class="call-form-item">
<label for="email">Email *</label>
<div class="input-wrapper">
<input class="js-form-call-email" id="email" type="email" name="email">
</div>
</div>
</div>
<div class="col-md-6">
<div class="call-form-item">
<div class="input-wrapper">
<input class="js-form-call-check1" id="check1" name="check1" type="checkbox"><label>Check 1</label>
<input class="js-form-call-check2" id="check2" name="check2" type="checkbox"><label>Check 2</label>
</div>
</div>
</div>
</form>
</div>
And here is an alternative, using radio buttons:
const inps=document.querySelectorAll(".input-wrapper input");
inps.forEach(e=>e.addEventListener("click",ev=>{
e.checked=e!==inps.last;
inps.last=e.checked?e:null
}))
<div class="input-wrapper">
<label><input name="radio" value="1" type="radio">Check 1</label>
<label><input name="radio" value="2" type="radio">Check 2</label>
<label><input name="radio" value="3" type="radio">Check 3</label>
</div>
Alternate solution:
HTML:
<section>
<label><input type="checkbox" value="CBox 1"> CBox 1</label>
<label><input type="checkbox" value="CBox 2"> CBox 2</label>
<label><input type="checkbox" value="CBox 3"> CBox 3</label>
<label><input type="checkbox" value="CBox 4"> CBox 4</label>
<label><input type="checkbox" value="CBox 5"> CBox 5</label>
</section>
<p> Checkbox acts like a radio button, but can be reset </p>
Javascript:
const sel = document.querySelectorAll('section input[type="checkbox"]');
for (el of sel) {
el.addEventListener('click',
function(e) { sel.forEach( (x) => { if (e.currentTarget != x) x.checked = false; } ); }
);
};
You can use JavaScript / jQuery for it. If check1 is active, just disable check2.
See change event and disabled

styling dropdown with checkboxes

I want to change the styling of a dropdown with check boxes using only CSS and javascript. I have added a picture of what I am trying to make when the button is pressed.. It would be nice if I could make a focus to the selected check box just like the grey container at the first checkbox
var expanded = false;
function showCheckboxes() {
var checkboxes = document.getElementById("checkboxes");
if (!expanded) {
checkboxes.style.display = "block";
expanded = true;
} else {
checkboxes.style.display = "none";
expanded = false;
}
}
.multiselect {
width: 200px;
}
.selectBox {
position: relative;
}
.selectBox select {
width: 100%;
font-weight: bold;
}
.overSelect {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
#checkboxes {
display: none;
border: 1px #dadada solid;
}
#checkboxes label {
display: block;
}
#checkboxes label:hover {
background-color: #1e90ff;
}
<form>
<div class="multiselect">
<div class="selectBox" onclick="showCheckboxes()">
<select>
<option>Group</option>
</select>
<div class="overSelect"></div>
</div>
<div id="checkboxes">
<label for="one">
<input type="checkbox" id="one" /> Boiler
</label>
<label for="two">
<input type="checkbox" id="two" /> Engine
</label>
<label for="three">
<input type="checkbox" id="three" /> Fan
</label>
<label for="one">
<input type="checkbox" id="four" /> Location
</label>
<label for="two">
<input type="checkbox" id="five" /> Ship
</label>
<label for="three">
<input type="checkbox" id="six" /> Valmarine
</label>
<label for="three">
<input type="checkbox" id="seven" /> Voyage</label>
</div>
</div>
</form>
For example I want to change the color of the dropdown button, the color of the box with the arrow on the right of the dropbox, the color of the checkboxes (dark grey) etc..
I am trying to make it as simple as possible using only CSS and javascript.
You can get pretty far on css alone. Most of the trick here is using a pseudo element on checkbox to represent selected state.
No html and js changes in this solution.
var expanded = false;
function showCheckboxes() {
var checkboxes = document.getElementById("checkboxes");
if (!expanded) {
checkboxes.style.display = "block";
expanded = true;
} else {
checkboxes.style.display = "none";
expanded = false;
}
}
* {
box-sizing: border-box;
}
body {
background: #0b4a79;
}
input[type="checkbox"]:checked::after {
border: 1px solid #a8a8a8;
background: #dadada;
background: linear-gradient(to bottom, #f0f0f0 0%, #c5c5c5 100%);
content: "";
left: 0;
right: 0;
top: 0;
bottom: 0;
position: absolute;
z-index: -10;
border-radius: 2px;
}
.multiselect {
width: 200px;
}
.selectBox {
position: relative;
}
.selectBox select {
width: 100%;
font-weight: bold;
background: #0000;
border: none;
border-radius: 2px;
background: linear-gradient(to bottom, #c9dde8 0%, #86b3cc 100%);
}
.overSelect {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
#checkboxes {
background-color: #103c5d;
display: none;
border: 1px #dadada solid;
margin: 5px 0 0 0;
border-radius: 3px;
}
#checkboxes label {
display: block;
font-family: Helvetica, Arial, sans-serif;
margin: 4px;
padding: 3px 2px;
position: relative;
color: #ffffff;
background: rgba(0, 0, 0, 0);
z-index: 1;
}
#checkboxes label:hover {
background-color: #1e90ff;
border-radius: 2px;
}
<form>
<div class="multiselect">
<div class="selectBox" onclick="showCheckboxes()">
<select>
<option>Group</option>
</select>
<div class="overSelect"></div>
</div>
<div id="checkboxes">
<label for="one">
<input type="checkbox" id="one" /> Boiler
</label>
<label for="two">
<input type="checkbox" id="two" /> Engine
</label>
<label for="three">
<input type="checkbox" id="three" /> Fan
</label>
<label for="one">
<input type="checkbox" id="four" /> Location
</label>
<label for="two">
<input type="checkbox" id="five" /> Ship
</label>
<label for="three">
<input type="checkbox" id="six" /> Valmarine
</label>
<label for="three">
<input type="checkbox" id="seven" /> Voyage</label>
</div>
</div>
</form>
To highlight the label you can go with something like mentioned in this post from #dfsq and add/remove a special class to your label on the click-event.
// get all your inputs within "#checkboxes label"
var checkedInput = document.querySelectorAll('#checkboxes label > input');
// loop over your inputs, by on change of your input (checked/unchecked)
// toggle the css class for the closest "label"
Array.from(checkedInput ).forEach(input => {
input.addEventListener('change', function(event) {
this.closest("label").classList.toggle("with-focus");
});
});
You can style then the new class
#checkboxes label.with-focus {
display: block;
background-color: #eee;
border-radius: 2px;
}
I've changed your snippet with this:
var expanded = false;
function showCheckboxes() {
var checkboxes = document.getElementById("checkboxes");
if (!expanded) {
checkboxes.style.display = "block";
expanded = true;
} else {
checkboxes.style.display = "none";
expanded = false;
}
}
// get all your inputs within "#checkboxes label"
var checkedInput = document.querySelectorAll('#checkboxes label > input');
// loop over your inputs, by on change of your input (checked/unchecked)
// toggle the css class for the closest "label"
Array.from(checkedInput ).forEach(input => {
input.addEventListener('change', function(event) {
this.closest("label").classList.toggle("with-focus");
});
});
.multiselect {
width: 200px;
}
.selectBox {
position: relative;
}
.selectBox select {
width: 100%;
font-weight: bold;
}
.overSelect {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
#checkboxes {
display: none;
border: 1px #dadada solid;
padding: 5px;
background-color: #103c5d;
}
#checkboxes label {
display: block;
}
#checkboxes label.with-focus {
display: block;
background-color: #eee;
border-radius: 2px;
}
#checkboxes label:hover {
background-color: #1e90ff;
}
<form>
<div class="multiselect">
<div class="selectBox" onclick="showCheckboxes()">
<select>
<option>Group</option>
</select>
<div class="overSelect"></div>
</div>
<div id="checkboxes">
<label for="one">
<input type="checkbox" id="one" /> Boiler
</label>
<label for="two">
<input type="checkbox" id="two" /> Engine
</label>
<label for="three">
<input type="checkbox" id="three" /> Fan
</label>
<label for="one">
<input type="checkbox" id="four" /> Location
</label>
<label for="two">
<input type="checkbox" id="five" /> Ship
</label>
<label for="three">
<input type="checkbox" id="six" /> Valmarine
</label>
<label for="three">
<input type="checkbox" id="seven" /> Voyage</label>
</div>
</div>
</form>
For all the other CSS stuff you should probably dig around, thats not as hard as its sounds ;)

Uncheck checked radio button by clicking on label using jQuery

I need to uncheck checked radio buttons using jQuery. The buttons themselves are hidden so I am using clicks on the labels to trigger this. So far I have:
HTML
<form>
<h4>Where would you like to work?</h4>
<div class="radio-holder">
<input id="form1_areas1" name="areas" type="radio" value="area/london">
<label for="form1_areas1">London</label>
</div>
<div class="radio-holder">
<input id="form1_areas2" name="areas" type="radio" value="area/west-midlands">
<label for="form1_areas2">West Midlands</label></div>
</form>
SCSS
form {
max-width: 500px;
margin: 0 auto;
padding-top: 20px;
}
div.radio-holder {
padding: 10px;
}
input[type="radio"] {
display:none;
&:checked+label {
border-bottom: 2px solid #222222;
padding-bottom: 0px;
}
}
JQUERY
$(document).ready(function(){
$("form input[type='radio']:checked + label").click(function(){
$(this).prev().prop( "checked", false );
});
});
Here a CodePen
But this isn't unchecking the radio button. I understand this is not standard functionality for radio buttons, but I need the user to be able to revert the set of radio buttons to their unselected state if desired, while also limiting them to selecting one from the set of options. Any help greatly appreciated.
Cheers
Mike
To enable/disable same radio , You have to use event.preventDefault() to prevent default behavior ( enabling check box when clicking on label, so checked prop will be always set to true ) and make radio enable / disable grammatically as shown in the below snippet :
$(document).ready(function(){
$("label").click(function(e){
e.preventDefault();
$check = $(this).prev();
if($check.prop('checked'))
$check.prop( "checked", false );
else
$check.prop( "checked", true );
//console.log($check.prop("checked"));
});
});
form {
max-width: 500px;
margin: 0 auto;
padding-top: 20px;
}
div.radio-holder {
padding: 10px;
}
input[type="radio"] {
display:none;
}
input[type="radio"]:checked+label {
border-bottom: 2px solid #222222;
padding-bottom: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<h4>Where would you like to work?</h4>
<div class="radio-holder">
<input id="form1_areas1" name="areas" type="radio" value="area/london">
<label for="form1_areas1">London</label>
</div>
<div class="radio-holder">
<input id="form1_areas2" name="areas" type="radio" value="area/west-midlands">
<label for="form1_areas2">West Midlands</label></div>
</form>
You could use next trick:
-Add a data-num attribute.
-Play with data-num on each click to check/uncheck the radio buttons.
Hope it helps:
$(document).ready(function(){
$("input").click(function(){
$("input").not(this).attr("data-num", 1);
var data = $(this).attr("data-num")
if(data==1){
data = 2
$(this).attr("data-num", data);
return;
}
if(data==2){
data = 1
$(this).prop('checked', false);
$(this).attr("data-num", data);
return;
}
})
})
form {
max-width: 500px;
margin: 0 auto;
padding-top: 20px;
}
div.radio-holder {
padding: 10px;
}
input[type="radio"] {
display:none;
}
input[type="radio"]:checked+label {
border-bottom: 2px solid #222222;
padding-bottom: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<h4>Where would you like to work?</h4>
<div class="radio-holder">
<input id="form1_areas1" name="areas" type="radio" value="area/london" data-num="1">
<label for="form1_areas1">London</label>
</div>
<div class="radio-holder">
<input id="form1_areas2" name="areas" type="radio" value="area/west-midlands" data-num="1">
<label for="form1_areas2">West Midlands</label></div>
</form>

How to uncheck a checkbox when another one is checked?

With Javascript, I would like one first checkbox to get unchecked when I check the second one. I also would like that the two checkboxes can be unchecked after having been checked.
Here is my HTML code :
<input type="checkbox" id="radio-1" class="radio" /><label for="radio-1">Yes</label>
<input type="checkbox" id="radio-2" class="radio" /><label for="radio-2">No</label>
I tried with two checkboxes, but I don't manage to uncheck #1 when #2 is checked.
Here is my Jsfiddle with the example with two checkboxes:
http://jsfiddle.net/3f66j30y/
I also tried with two radio buttons, but I don't manage to remain them unchecked after having been checked.
Add an onclick event to each checkbox to uncheck the other checkbox
input[type="checkbox"] {
display:none;
}
input[type="checkbox"] + label
{
padding:10px 10px;
text-align:center;
background:#dedede;
color:black;
height: 20px;
width: 100px;
display:inline-block;
}
input[type="checkbox"]:checked + label
{
padding:10px 10px;
text-align:center;
background:green;
color:white;
height: 20px;
width: 100px;
display:inline-block;
}
<input type="checkbox" id="radio-1" class="radio" onclick="document.getElementById('radio-2').checked = false"/><label for="radio-1">Yes</label>
<input type="checkbox" id="radio-2" class="radio" onclick="document.getElementById('radio-1').checked = false"/><label for="radio-2">No</label>
The following in a Vanilla JS solution, which:
binds change events when the DOM is loaded
only binds one change event to the parent container
in the change event, decides what the target is and turns off other checkboxes
document.addEventListener('DOMContentLoaded', function() {
document.querySelector('.select-group').onchange = changeEventHandler;
}, false);
function changeEventHandler(e) {
var cbs = document.querySelectorAll('.cb');
cbs.forEach(function(cb) {
if (cb != e.target)
cb.checked = false;
});
}
input[type="checkbox"] {
display: none;
}
label {
padding: 10px 10px;
text-align: center;
background: #dedede;
color: black;
height: 20px;
width: 100px;
display: inline-block;
}
input[type="checkbox"]:checked+label {
padding: 10px 10px;
text-align: center;
background: green;
color: white;
height: 20px;
width: 100px;
display: inline-block;
}
<div class="select-group">
<input id="cb_yes" type="checkbox" value="yes" class="cb" />
<label for="cb_yes">Yes</label>
<input id="cb_no" type="checkbox" value="no" class="cb" />
<label for="cb_no">No</label>
</div>
It can certainly be improved; after all, one obvious point is that you're searching the DOM for the checkboxes every time they change — you could easily cache them. However, this should serve a point and show you how easy it is to work with standard JS.
Use jQuery to achieve this.
$(".radio").change(function() {
var checked = $(this).is(':checked');
$(".radio").prop('checked',false);
if(checked) {
$(this).prop('checked',true);
}
});
input[type="checkbox"] {
display:none;
}
input[type="checkbox"] + label
{
padding:10px 10px;
text-align:center;
background:#dedede;
color:black;
height: 20px;
width: 100px;
display:inline-block;
}
input[type="checkbox"]:checked + label
{
padding:10px 10px;
text-align:center;
background:green;
color:white;
height: 20px;
width: 100px;
display:inline-block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="radio-1" class="radio" /><label for="radio-1">Yes</label>
<input type="checkbox" id="radio-2" class="radio" /><label for="radio-2">No</label>
Behavior you are looking for is specific to radio buttons. However the problem is - you can't uncheck it, once checked. In this case you can use three radio buttons - yes, no and none (-) - since clearly you want more then two options:
<input type="radio" id="radio-0" name="group-one" class="radio" checked /><label for="radio-0">-</label><br>
<input type="radio" id="radio-1" name="group-one" class="radio" /><label for="radio-1">Yes</label><br>
<input type="radio" id="radio-2" name="group-one" class="radio" /><label for="radio-2">No</label>
If you prefer to stick with two, you can use your checkboxes with a bit of JavaScript to switch the opposite box off:
function radioSwitch(opposite) {
document.getElementById(opposite).checked = false;
}
document.getElementById("radio-1").addEventListener("click",
function() { radioSwitch("radio-2"); });
document.getElementById("radio-2").addEventListener("click",
function() { radioSwitch("radio-1"); });
<input type="checkbox" id="radio-1" class="radio" /><label for="radio-1">Yes</label>
<input type="checkbox" id="radio-2" class="radio" /><label for="radio-2">No</label>

Jquery failed to change Div border colour

I am trying to implement "changing Div border color" when clicking on one of the radio buttons. It works well for scenario 1 but won't work on scenario 2.
$(":radio:checked").closest(".discount").addClass("checked");
$(":radio").on("change", e => {
const $div = $(e.target).closest(".discount");
console.log($div);
$(".discount").removeClass("checked");
$div.addClass("checked");
});
$(":radio:checked").closest(".discount2").addClass("checked");
$(":radio").on("change", e => {
const $div = $(e.target).closest(".discount2");
console.log($div);
$(".discount2").removeClass("checked");
$div.addClass("checked");
});
.discount {
border: 2px solid #cccccc;
padding: 2px;
padding: 10px;
width: 100%;
text-align: center;
border-radius: 5px;
}
.discount.checked {
border-color: red;
}
.discount2 {
border: 2px solid #cccccc;
padding: 2px;
padding: 10px;
width: 100%;
text-align: center;
border-radius: 5px;
}
.discount2.checked {
border-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label style="width:100%">
<div class="discount">
<input type="radio" name="fruits" checked>Apple</div>
</label>
<label style="width:100%">
<div class="discount">
<input type="radio" name="fruits">Banana</div>
</label>
<label style="width:100%">
<div class="discount2">
<input type="radio" name="drinks" checked>Milk</div>
</label>
<label style="width:100%">
<div class="discount2">
<input type="radio" name="drinks">Zzz</div>
</label>
<label style="width:100%">
<div class="discount2">
<input type="radio" name="drinks">Bbb</div>
</label>
In scenario 2, when clicking on 'Zzz', the Div border "Red" is gone! Anyone know whats wrong ?
There is no need to use multiple clases and such:
(I added another version of the example, where no <div>s were used (and changed the coloring a bit)
$('input[type=radio]:checked').parent().addClass('checked');
$('input[type=radio]').on('change',function(e) {
var thisGroup = $(this).attr('name');
if ($(this).is(':checked')) {
$('input[name='+thisGroup+']').parent().removeClass('checked');
$(this).parent().addClass('checked');
}
});
.discount, .discount-label{
border: 2px solid #cccccc;
padding:2px;
padding:10px;
width:10%;
text-align:center;
border-radius: 5px;
}
.discount.checked,.discount-label.checked {
border-color: red;
}
.discount-label input[type=radio] {
display: none;
}
.discount-label.checked {
background: red;
color: #FFF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><div class="discount"><input type="radio" name="fruits" checked>Apple</div></label>
<label><div class="discount"><input type="radio" name="fruits">Banana</div></label>
<label><div class="discount"><input type="radio" name="drinks" checked>Milk</div></label>
<label><div class="discount"><input type="radio" name="drinks">Zzz</div></label>
<label><div class="discount"><input type="radio" name="drinks">Bbb</div></label>
<h2>example two</h2>
<label class="discount-label"><input type="radio" name="fruits2" checked>Apple</label>
<label class="discount-label"><input type="radio" name="fruits2">Banana</label>
<label class="discount-label"><input type="radio" name="drinks2" checked>Milk</label>
<label class="discount-label"><input type="radio" name="drinks2">Zzz</label>
<label class="discount-label"><input type="radio" name="drinks2">Bbb</label>
The problem is that both $(":radio").on("change") are triggered and both the .checked classes are removed but it's only added the current changed checkbox. You can use 1 css class instead or change the javascript to remove all checked classes and add them back like you do on a page load.
updateBorders();
$(":radio").on("change", e => {
const $div = $(e.target).closest(".discount");
console.log($div);
updateBorders();
});
function updateBorders() {
$(".discount").removeClass("checked");
$(".discount2").removeClass("checked");
$(":radio:checked").closest(".discount").addClass("checked");
$(":radio:checked").closest(".discount2").addClass("checked")
}
Full JSFiddle here.

Categories

Resources