How to add addition class in JS to the div or table , when radio input is checked ?
I would like add class table-selected , to the div class="table-item"
when I checked a radio input .
$(".table-item input").change(function() {
var div = $(this).closest('.table-item');
$(this).is(":checked") ? div.addClass("table-selected") : div.removeClass("table-selected");
});
#test .table-item {
border: solid 1px #666;
height: 25px;
background-color: #CCC
}
#test .table-selected {
border: 1 px solid #F00;
background-color: #00F
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="test">
<div class="table-item">
<div><label for="check1"><input type='radio' name='rad' value='1'>1</label></div>
</div>
<div class="table-item">
<div><label for="check2"><input type='radio' name='rad' value='2'>2</label></div>
</div>
<div class="table-item">
<div><label for="check3"><input type='radio' name='rad' value='3'>3</label></div>
</div>
</div>
But this work some wrong , add class , but it does not remove it when unchecked
You have to remove class from other before adding to current. Triggers fire for only that element, so check will run for that element not others.
Update Link: https://jsfiddle.net/m637ndrx/2/
$(".table-item input").change(function() {
var div = $(this).closest('.table-item');
$('.table-item').removeClass("table-selected")
$(this).is(":checked") ? div.addClass("table-selected") : div.removeClass("table-selected");
});
You are just removing the class from the selected div. The else part of that ternary condition would never be satisfied because there div represents the button that you selected.
You need to remove the class from all the divs.
$(".table-item").removeClass('table-selected');
var div = $(this).closest('.table-item');
if ($(this).is(":checked")) {
div.addClass("table-selected");
}
Check here: https://jsfiddle.net/g5o2w47v/
Related
I'm currently building a form that has checkboxes wrapped inside of labels. We are doing this because we need to swap our the original checkbox for an image. However, when the checkbox is checked, we need to make the label have a border to give some user feedback.
Here is the setup of the labels/checkboxes
<div class="one_column">
<label for="fieldname2_1_cb0">
<input name="fieldname2_1[]" id="fieldname2_1_cb0" class="field depItem group required" value="Alloy Wheel(s)" vt="Alloy Wheel(s)" type="checkbox"> <span>Alloy Wheel(s)</span>
</label>
</div>
We have tried going about is using the following but obviously doesn't work
label input[type="checkbox"]:checked + label {
border: 5px solid blue;
}
Any help would be appreciated!
I have managed to the the first checkbox using the code supplied below
window.onload=function() {
document.querySelector('input[type="checkbox"]').addEventListener('change',
function() {
if (this.checked) {
this.parentNode.classList.add('border-blue');
} else {
this.parentNode.classList.remove('border-blue');
}
})}
However, it only changes the first checkbox... there are 10 in total all following the same structure as above
Using CSS, there is no way to select parent elements from child elements.
If you are allowed to use JavaScript, you can solve it this way:
document.querySelectorAll('input[type="checkbox"]').forEach(function(el) {
el.addEventListener('change', function() {
if (this.checked) {
this.parentNode.classList.add('border-blue');
} else {
this.parentNode.classList.remove('border-blue');
}
})
})
.border-blue {
border: 5px solid blue;
}
It will check for changes on input. If it is checked, a class will be added. Otherwise, the class will be removed.
I have to make a real simple task but I cannot figure it out.
I have some cards that the user can select with a radio button. I want to higlight the selected card when the user click on the relative input radio.
I don't understand how can I select the closest class of the selected radio.
My HTML looks like this:
<div class="box">
<div class="box-content">
<input type="radio" name="box-input">
<label>Label One</label>
</div>
</div>
<div class="box">
<div class="box-content">
<input type="radio" name="box-input">
<label>Some Two</label>
</div>
</div>
And so on...
<button onclick="submit()">Submit</button>
If I do like this:
let boxes = document.querySelectAll('input');
const submit = () => {
for (let i=0;i<boxes.length;i++) {
boxes[i].checked? this.closest('.box').classList.add('selected'): console.log('nothing is selected')
}
}
It says that this.closest is undefined, and it works only if the user click on the submit button.
What I want to do is just add a class to div .box when the radio input is selected, and remove it when change the state to unselected.
I'd like also to avoid the inline HTML "onclick" if possible.
Please pure javascript only
EDIT
With the suggestion of #somethinghere I added onchange="change(this)" to each input radio and I change my script in this way:
const change = el => {
el.checked?el.closest('.box').classList.add('selected'):el.closest('.box').classList.remove('selected')
;
It works, it adds the class selected when I click on a input radio. But if I click on another input, then the class selected is not removed.
Suggestions?
Added code to change the style of closest class when input radio is selected
var radioAll = document.querySelectorAll('input');
for(var i = 0; i < radioAll.length; i++)
{
radioAll[i].onclick = function()
{
//remove selected class from all box classs
var boxElems = document.querySelectorAll(".box");
[].forEach.call(boxElems, function(el) {
el.classList.remove("selected");
});
if(this.checked)
{
this.closest('.box').classList.add('selected');
}
};
}
.selected{
background-color: coral;
}
<div class="box">
<div class="box-content">
<input type="radio" name="box-input">
<label>Label One</label>
</div>
</div>
<div class="box">
<div class="box-content">
<input type="radio" name="box-input">
<label>Some Two</label>
</div>
</div>
And so on...
<button onclick="submit()">Submit</button>
While you've already accepted an answer, I thought I'd add an alternative approach:
// get a reference to the <button> element; here you only have the one <button>,
// so document.querySelector() will suffice (as it returns either the first
// Node that matches the supplied selector or null):
let submitButton = document.querySelector('button'),
inputs = document.querySelectorAll('input');
// here we use the same Arrow function syntax, which does not - by design - get
// its own 'this' reference:
const submit = () => {
// since we have the <input> elements already we use that, along with the
// NodeList.prototype.forEach() method:
inputs.forEach(
// here 'input' is a reference to the current <input> element of the
// NodeList of <input> elements over which we're iterating.
// we use Element.closest() to find the relevant '.box' element, and
// use the Element.classList API to toggle the 'hasSelected'
// class-name based on the supplied 'switch', the 'input.checked'; if
// 'input.checked' is true the class-name is added to the '.box', if
// 'input.checked' is false the class-name is removed (if the class-name
// is already present, or not-present, when it's added or removed no
// error is thrown and it presents no problem):
(input) => input.closest('.box').classList.toggle('hasSelected', input.checked)
)
}
// using the EventTarget.addEventListener() method, in place of the obtrusive
// 'onclick' in-line event-handling; here we bind the submit() function
// (note the deliberate lack of parentheses) as the event-handler for the
// 'click' event:
submitButton.addEventListener('click', submit);
*,
::before,
::after {
box-sizing: border-box;
margin: 0;
padding: 0;
font-size: 1rem;
line-height: 1.5;
}
body>div {
display: flex;
justify-content: space-between;
width: 50vw;
margin: 1em auto;
}
div.box {
display: grid;
grid-template-columns: 1fr 30px;
grid-gap: 0 10px;
border: 2px solid transparent;
padding: 0.5em;
border-radius: 1em;
}
div.box.hasSelected {
border-color: limegreen;
}
div.box.hasSelected::after {
display: contents;
content: '✓';
font-weight: bold;
color: limegreen;
}
<div>
<div class="box">
<div class="box-content">
<label><input type="radio" name="box-input">
Label One</label>
</div>
</div>
<div class="box">
<div class="box-content">
<label><input type="radio" name="box-input">
Some Two</label>
</div>
</div>
<button>Submit</button>
</div>
JS Fiddle demo.
References:
Arrow functions.
Document.querySelector().
Element.classList API.
Element.closest().
EventTarget.addEventListener().
NodeList.prototype.forEach().
I can get the follow code to work like I want it to with one exception.
When I select the checkbox the background color of the div changes from #fff to #ffe600 as it should. The problem I'm running into is when the form is submitted and page is refreshed the background color reverts back to #fff. I would like for the back ground color to stay #ffe600 when the page is refreshed after the form has been submitted. The checkbox remains checked after page refresh but the div background color reverts back to #fff. Does anyone know if it's possible to maintain the div background color #ffe600 when the page is refreshed. This has really gotten be stumped.
function myFunction(x, _this) {
if (_this.checked) {
x.style.backgroundColor = '#ffe600';
} else {
x.style.backgroundColor = '#fff';
}
}
#product1 {
background-color: #fff;
padding: 3px 5px 3px 7px;
margin-top: 6px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="product1">
<label class="chk">
<input type="checkbox" onChange="myFunction(product1, this)" name="select_product" value="Y" />Label goes here.</label>
</div>
Thanks!
One option is to check on load with jquery and then highlight the currently checked boxes.
$('input[type=checkbox]').each(function(){
if($(this).is(':checked'))
$(this).parent().parent().css('backgroundColor','#ffe600');
else
$(this).parent().parent().css('backgroundColor','#fff');
});
function myFunction(x, _this) {
if (_this.checked) {
x.style.backgroundColor = '#ffe600';
} else {
x.style.backgroundColor = '#fff';
}
}
#product1 {
background-color: #fff;
padding: 3px 5px 3px 7px;
margin-top: 6px;
}
#product2 {
background-color: #fff;
padding: 3px 5px 3px 7px;
margin-top: 6px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="product1">
<label class="chk">
<input type="checkbox" onChange="myFunction(product1, this)" name="select_product" value="Y" />Label goes here.</label>
</div>
<div id="product2">
<label class="chk">
<input checked type="checkbox" onChange="myFunction(product2, this)" name="select_product2" value="V" />Label goes here 2.</label>
</div>
Is there a need to actually refresh the page? It looks like you're using AJAX.
Do you use a function to handle the submit of the form? Cause then you could do the following to prevent the page from reloading
<form onsubmit="submitFunction(event)">
// form elements
</form>
And the JavaScript part like the following
function submitFunction(event) {
event.preventDefault();
// form data processing
}
The event.preventDefault() will keep the page from reloading which should keep the background color of your element.
You can use localstorage or Cookie to store the state of checkbox and later when page loads you can get the state from them or else you can do the same check as in myFunction when page loads as below :
window.onload = function(){
var checkBoxEle = document.querySelector("div#product1 input[type='checkbox']");
var productEle = document.getElementById("product1");
if (checkBoxEle.checked) {
productEle.style.backgroundColor = '#ffe600';
} else {
productEle.style.backgroundColor = '#fff';
}
You can make a function using jquery that can be used for checkbox validation and formatting when the document is loaded and when the checkbox is clicked.
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var setColor = function(){
if($("#select_product").is(":checked")) $("#product1").css("background-color", "#ffe600");
else $("#product1").css("background-color", "#fff");
}
$(document).ready(function(){
setColor();
$("#select_product").click(setColor);
});
</script>
<div id="product1">
<label class="chk">
<input type="checkbox" id="select_product" value="Y">Label goes here.</label>
</div>
</body>
</html>
Code below makes that on each click all checkboxes which are not disabled, are checked/unchecked. Also at the first click background of chackboxes parents are chanhging to red.
var clicked = false;
var target = jQuery(".editcheckhour:not(:disabled)");
jQuery(".checkalledit").click(function() {
target.prop("checked", !clicked).closest('label').css('background-color','#c00');
clicked = !clicked;
});
On next click I want to change background color back. So the function will not only check/uncheck inputs but also will alternately change checkboxes parents background.
On this JSFIdle demo only first click change backgrounds.
https://jsfiddle.net/xLg7eszb/1/
Is anybody help me do this?
Try using toggleClass()
var clicked = false;
var target = jQuery(".editcheckhour:not(:disabled)");
jQuery(".checkalledit").click(function() {
target.prop("checked", !clicked).closest('label').toggleClass('bgcolor');
clicked = !clicked;
});
label {
background-color: #558;
color: white;
padding: 5px 12px;
}
label > input:disabled {
opacity: 0.5
}
button {
display: block;
margin-top: 20px;
}
.bgcolor {
background-color: #c00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<label>
<input class="editcheckhour" type="checkbox">onet</label>
<label>
<input disabled class="editcheckhour" type="checkbox">two</label>
<label>
<input class="editcheckhour" type="checkbox">three</label>
<label>
<input class="editcheckhour" type="checkbox">four</label>
<button type="button" class="checkalledit">on / off</button>
Its simple. Add one class to label default in your code and define that class as default color in your css file.
<label><input class="editcheckhour defaultColor" type="checkbox"> onet</label>
<label><input disabled class="editcheckhour defaultColor" type="checkbox"> two</label>
<label><input class="editcheckhour defaultColor" type="checkbox"> three</label>
<label><input class="editcheckhour defaultColor" type="checkbox"> four</label>
the defaultColor class will be in css like
defaultColor {
background-color: #558;
}
another new color will be red like this.
newColor {
background-color: red;
}
on button click simply remove the class and add class to labels on status of the button. To maintain button status write code as:
<button type="button" class="checkalledit" data-status="0">on / off</button>
after click it will change label background first and then change self status.
jQuery(".checkalledit").click(function() {
var status = $(this).attr("data-status");
if(status == 0){
target.prop("checked", !clicked).closest('label').removeClass("defaultColor");
target.prop("checked", !clicked).closest('label').addClass("newColor");
$(this).attr("data-status","1");
}
else{
target.prop("checked", !clicked).closest('label').removeClass("newColor");
target.prop("checked", !clicked).closest('label').addClass("defaultColor");
$(this).attr("data-status","0");
}
});
I am looking to have a checkbox (Football) that when
Unchecked:
displays one DIV (FootballChoice) containing a label image for the checkbox that changes with mouseover
Checked:
hides the DIV (FootballChoice)
shows a hidden DIV (FootballChecked) that contains an alternate label image
shows another hidden DIV (FootballTeams).
When unchecked again, this needs to return to it's original state.
Alternatively if anyone knows how to change the label image when checked to the same as the one specified in the mouseover element here, that would also be a usefull altetrnative?
Thank you in advance.
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
if($(this).attr("value")=="FootballTeams"){
$(".FootballTeams").toggle();
$(".FootballChecked").toggle();
$(".FootballChoice").toggle();
}
});
});
</script>
.FootballChecked {
display: none;
}
.FootballChoice {
display: show;
}
.sport {
display: none;
border: 1px dashed #FF3333;
margin: 10px;
padding: 10px;
background: #003366;
}
<input id="Football" type="checkbox" value="FootballTeams">
<div class="FootballChoice">
<label for="Football" class="FootballChoice">
<img src="http://web.static.nowtv.com/email-marketing/assets/structure/SPORTSPREF_FOOTBALL_100x130.png" onmouseover="this.src='http://web.static.nowtv.com/email-marketing/assets/structure/SPORTSPREF_FOOTBALL_NAME_100x130.png';" onmouseout="this.src='http://web.static.nowtv.com/email-marketing/assets/structure/SPORTSPREF_FOOTBALL_100x130.png';" alt="Football" title="Football">
</label>
</div>
<div class="FootballChecked">
<label for="Football">
<img src="http://web.static.nowtv.com/email-marketing/assets/structure/SPORTSPREF_FOOTBALL_NAME_100x130.png" alt="Football" title="Football">
</label>
</div>
<div class="sport FootballTeams">
Football Teams here
</div>
Do you have to use JavaScript? You could use the CSS Pseudo-selector :checked and the General Siblings Selector to display elements based on whether the checkbox is :checked or not.
E.G:
#football {opacity:0.2;}
.checked {display:none;}
#football:checked ~ .unchecked {display:none;}
#football:checked ~ .checked {display:block;}
label {
display:inline-block;
border:1px solid blue;
padding:20px;
background:url(http://lorempixel.com/100/100/sports)
}
label:hover {
border-color:red;
background:url(http://lorempixel.com/100/100/cats)
}
div {border:1px dotted green;}
<input id="football" type="checkbox" value="1" />
<div class="unchecked">
Unchecked:
displays one DIV
<div id="FootballChoice">
(FootballChoice) containing a
<label for="football">label image for the checkbox that changes with mouseover</label>
</div>
</div>
<div class="checked">
Checked:
hides the DIV (FootballChoice)
shows a hidden DIV
<div id="FootballChecked">
(FootballChecked) that contains an
<label for="football">alternate label image</label>
</div>
shows another hidden DIV .
<div id="FootballTeams">
(FootballTeams)
</div>
When unchecked again, this needs to return to it's original state.
</div>
http://jsfiddle.net/zpz3mvuv/