How can I change style of parent elements of checked checkboxes - javascript

I'm using Asp.Net CheckBoxList control and I have a lot of checkboxes inside li elements. I want to change background color of li elements if the checkbox is checked inside it. I tried lots of things with css and jquery but i couldn't do it.
Note: Some of the answers given below are working when I click checkboxes. But when the page is postback, the checked boxes are turning to default view.
<ul id="ContentPlaceHolder1_CheckBoxList1">
<li><input id="c1" type="checkbox" name="c1" value="57" /><label for="c1">aaaaaaaaa</label></li>
<li><input id="c2" type="checkbox" name="c2" value="94" /><label for="c2">bbbbbbbbbb</label></li>
<li><input id="c3" type="checkbox" name="c3" value="121" /><label for="c3">cccccccccc</label></li>
</ul>
Some of my tries:
<!-- 1 -->
var ccc = function () {
$("input:checked").parent("li").css({"color": "white", "background-color": "blue"});
};
ccc();
$( "input[type=checkbox]" ).on( "click", ccc );
<!-- 2 -->
$(":checkbox").click(function(){
$(":checked").parent().css({"color": "white", "background-color": "blue"});
});
/*1*/
li < input[type=checkbox]:checked {
background-color:aqua;
}
/*2*/
li:has( input[type="checkbox"]:checked) {
background: #000;
border-color: green;
color: white;
}

Use jquery is() function and elem.closest() function.You can add or remove class based on input condition using change event
$(document).on('change','#ContentPlaceHolder1_CheckBoxList1 input[type=checkbox]',function(){
if($(this).is(':checked')){
$(this).closest('li').addClass('checked_class')
}else{
$(this).closest('li').removeClass('checked_class')
}
})
.checked_class{
border:1px solid red;
/*add your desgin properties*/
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="ContentPlaceHolder1_CheckBoxList1">
<li>
<input id="c1" type="checkbox" name="c1" value="57" />
<label for="c1">aaaaaaaaa</label>
</li>
<li><input id="c2" type="checkbox" name="c2" value="94" /><label for="c2">bbbbbbbbbb</label></li>
<li><input id="c3" type="checkbox" name="c3" value="121" /><label for="c3">cccccccccc</label></li>
</ul>

Using vanilla javascript you could do the following. Using the change event listener you can check whether the checkbox has been checked or not. If it evaluates true it means it has been checked by the user. In that case you can get its parent by using parentNode object on the element to get manipulate its styles.
const inputs = document.querySelectorAll('input');
const color = ['blue', 'red', 'yellow'];
inputs.forEach((input, index) => {
input.addEventListener('change', function(){
if(this.checked){
this.parentNode.style.background = color[index]
}
})
})

Thanks everybody. I solved the problem your way (mixing your answers).
I used two functions. One of them is working on page load and controlling all checkboxes if they are checked or not, other is working when a checkbox changes.
$(document).ready(function () {
$("input").each(function (index) {
if ($(this).is(':checked')) {
$(this).parent().css('background-color', 'blue');
}
else {
$(this).parent().css('background-color', '#eee');
}
});
});
$('#ContentPlaceHolder1_CheckBoxList1 input[type=checkbox]').on('change', function () {
if ($(this).is(':checked')) {
$(this).parent().css('background-color', 'blue');
}
else {
$(this).parent().css('background-color', '#eee');
}
});

With usual Javascript:
window.onload = function a() {
document.querySelectorAll("li").forEach(function(e) {
if (e.children[0].checked == true) e.style.backgroundColor = "green";
else e.style.backgroundColor = "";
e.onchange = a;
})
}
<ul id="ContentPlaceHolder1_CheckBoxList1">
<li><input id="c1" type="checkbox" name="c1" value="57" /><label for="c1">aaaaaaaaa</label></li>
<li><input id="c2" type="checkbox" name="c2" value="94" /><label for="c2">bbbbbbbbbb</label></li>
<li><input id="c3" type="checkbox" name="c3" value="121" /><label for="c3">cccccccccc</label></li>
</ul>

You want to listen to the change event of the checkbox, then target the parent element (li). My example below simply changes the background of the li using $.css(). You could add a class using .addClass("className").
Edit: I've updated my answer now you need on load behaviour.
The code below uses a ES6 style function definition using an arrow functions. It takes 2 parameters (id, isChecked) and updates the css accordingly. toggleStyle function uses the ternary operator which is equivalent to an if{} else{} block.
// on load
$(document).ready(function(){
$('li input[type=checkbox]').each(function() {
// pass the id and isChecked to toggleColour
toggleStyle(this.id, $(this).is(':checked'));
});
});
// on change
$('li input[type=checkbox]').on('change', function() {
// pass the id and isChecked to toggleColour
toggleStyle(this.id, $(this).is(':checked'));
});
// ES6 function defn to toggle colour/style
var toggleStyle = (id, isChecked) =>
{
isChecked ? $('#'+id).parent().css('background', '#ff0')
: $('#'+id).parent().css('background', '#fff')
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="ContentPlaceHolder1_CheckBoxList1">
<li><input id="c1" type="checkbox" name="c1" value="57" /><label for="c1">aaaaaaaaa</label></li>
<li><input id="c2" type="checkbox" name="c2" value="94" checked /><label for="c2">bbbbbbbbbb</label></li>
<li><input id="c3" type="checkbox" name="c3" value="121" /><label for="c3">cccccccccc</label></li>
</ul>

Related

Check\Uncheck all the items in the List - Visual Studio LightSwitch

I am using Visual Studio LightSwitch 2015
I have added Countries Table from SQL Server and for each Country in the List, I have CheckBox
Now I have placed a CheckBox at the top of the List Using Custom Control
myapp.Countries.CheckAll_postRender = function (element, contentItem) {
var checkbox = $("<input type='checkbox'/>")
.css({
height: 20,
width: 20,
left:-26,
margin: "45px"
})
.appendTo($(element));
};
How can I Select\DeSelect All the CheckBoxes in the List with single Click of the CheckBox at the top of the Table?
Any help would be greatly appreciated.
Although the above code example works, you can actually do it faster assuming the checkboxes you want to check are the only ones on the page (besides the "check all" checkbox).
The below checks all checkboxes on the page except the "Check All" one.
$("#checkAll").click(function () {
$('input:checkbox').not(this).prop('checked', this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="checkAll">Check All
<hr />
<input type="checkbox" id="checkItem">Item 1
<input type="checkbox" id="checkItem">Item 2
<input type="checkbox" id="checkItem">Item3
Here's a simple example from this post Check/Uncheck all the checkboxes in jQuery
$(document).ready(function() {
$('#select-all').click(function(event) {
if(this.checked) {
$('.checkitem').each(function() {
this.checked = true;
});
}else{
$('.checkitem').each(function() {
this.checked = false;
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><label>item-1</label><input name="checkbox-1" id="checkbox-1" type="checkbox" class="checkitem" /></li>
<li><label>item-1</label><input name="checkbox-2" id="checkbox-2" type="checkbox" class="checkitem" /></li>
<li><label>item-1</label><input name="checkbox-3" id="checkbox-3" type="checkbox" class="checkitem" /></li>
<li><label>item-1</label><input name="checkbox-4" id="checkbox-4" type="checkbox" class="checkitem" /></li>
</ul>
<input type="checkbox" name="select-all" id="select-all" /> Check all

Posting div/text when box checked

I'm relatively new to JS and was looking for an article or method in which to accomplish the following - be it a form or just JS. (Would like to avoid PHP.)
I have a series of check boxes call them box 1 - 4, which when any one is checked should either show a div or post text to a particular div on the page.
Example: when box 1 is checked div A posts "Box one has been checked."
I'm not certain how to refine my searches to find an example of what I'm looking for but did find a jsfiddle with a similar technique this posts a textbox under the checkbox when activated.
DEMO
<input id="chk" type="checkbox" value="results" />Results
<div id="formContainer"></div>
var textboxId = 0;
function CreateTextbox() {
var textBox = document.createElement("input");
textBox.setAttribute("type", "textbox");
textBox.setAttribute("id", textboxId);
textboxId++;
return textBox;
}
document.getElementById("chk").onclick = function () {
if (textboxId == 0) {
document.getElementById("formContainer").appendChild(CreateTextbox(textboxId));
textboxId = 1;
} else if (textboxId == 1) {
document.getElementById("formContainer").innerHTML = '';
textboxId = 0;
//The code to remove the previosuly made textbox
}
}
Any direction or code ideas are appreciated. Thanks!
Hope this is what you are expecting.
$('.chkbox').on('click',function(){
if($(this).is(':checked')) //check if checkbox is checked or unchecked
{
$(this).next('.formContainer').html('<div class="new">'+$(this).data('detail')+'</div>');
//get detail to add from the clicked checkbox's data-* attribute
}
else
{
$(this).next('.formContainer').html('');
//just empty the html below it
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="chk" data-detail="Box one has been checked." class="chkbox" type="checkbox" value="results" />Results
<div class="formContainer"></div>
<input id="chk2" data-detail="Box two has been checked." class="chkbox" type="checkbox" value="results" />Results
<div class="formContainer"></div>
<input id="chk3" data-detail="Box three has been checked." class="chkbox" type="checkbox" value="results" />Results
<div class="formContainer"></div>
<input id="chk4" data-detail="Box four has been checked." class="chkbox" type="checkbox" value="results" />Results
<div class="formContainer"></div>
Add detail for each checkbox in its data-detail property. Refer html above
Extenal Demo
Update
To display all the text in a single div you can just refer the target element as below:
$('.chkbox').on('click',function(){
if($(this).is(':checked'))
{
$('.formContainer').html('<div class="new">'+$(this).data('detail')+'</div>'); //directly refer the element
}
else
{
$('.formContainer').html('');
}
});
Updated demo
Not sure if this is what you really need, but this should help you get started, It also requires jquery
HTML
<input class="mychk" type="checkbox" value="Box 1 is Check" />Box 1<br>
<input class="mychk" type="checkbox" value="Box 2 Box is Check" />Box 2<br>
<input class="mychk" type="checkbox" value="Box 3 Box is Check" />Box 3<br>
<input class="mychk" type="checkbox" value="Box 4 Box is Check" />Box 4
<div class="showcheck">I'll Be Overwritten When Checkbox is check</div>
jQuery
(function($) {
//run for each input box
$('.mychk').each( function() {
// detect change action
$(this).change( function() {
// if the checkbox is check
if( $(this).is(':checked') ) {
//insert checkbox value in showcontent div
$('.showcheck').html( $(this).val() );
} else {
// if uncheck, assign default value
$('.showcheck').html( 'Default Content' );
}
});
});
})(jQuery);
Demo here
Pure JavaScript answer:
HTML:
<div id="checkboxes">
<input id="one" type="checkbox"></input>
<input id="two" type="checkbox"></input>
<input id="three" type="checkbox"></input>
</div>
<div id="answer"></div>
JS:
[].forEach.call(document.getElementById("checkboxes").children, function(element) {
element.onclick = function () {
document.getElementById("answer").innerHTML = element.id + " " + element.checked;
}
});
JSfidle

Change div color using multiple radio buttons and JavaScript

I'm trying to use radio buttons to change the background color of my div tag. I would like to use more than more condition. E.g., if button A is clicked and button B is clicked then make the color green.
This is what I have so far.
<div id="CLWarn">Warning Colour </div>
<input type="radio" name="IM" id="IM" value="1" onclick="A(this)"/>
<input type="radio" name="PB" id="PB" value="1" onclick="B(this)"/>
function A(chk) {
if(chk.checked == true) {
function B(chk) {
if(chk.checked == true) {
$(document).ready(function(){
document.getElementById("CLWarn").style.backgroundColor="Green";
document.getElementById("CLWarn").style.lineHeight=1.8;})
}}
}}
It works if I'm only using one condition (just clicking one button and only having the one function, but I don't know how to add another condition to my function.
Probably you try to do something like this:
function A(chk) {
if ( document.getElementById("IM1").checked && document.getElementById("IM2").checked ) {
document.getElementById("CLWarn").style.backgroundColor="Green";
document.getElementById("CLWarn").style.lineHeight=1.8;
}
}
<div id="CLWarn">Warning Colour </div>
<input type="radio" name="IM1" id="IM1" value="1" onclick="A(this)"/>
<input type="radio" name="IM2" id="IM2" value="1" onclick="A(this)"/>
Notice that there are different names for the radio buttons to allow multiple selection. And the ids are also unique according to some good practices.
Although jquery hasn't been tagged, as the OP has used it in his code, here is a jquery solution:
$('input').change(function() {
if ($('#IM').is(':checked')) {
if ($('#PB').is(':checked')) {
alert('green');
} else {
alert('blue');
}
} else {
alert('red');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="radio" name="IM" id="IM" value="1" />
<input type="radio" name="PB" id="PB" value="1" />
As has already been mentioned, your radio buttons have the same 'Name' value, meaning only one can be checked at a time.
If I understand correctly, you can achieve what you want using something like the following:
function changeColour(element) {
var div = document.getElementById('CLWarn');
if (element.id == 'a' && element.checked) {
div.style.backgroundColor = 'green';
} else if (element.id == 'b' && element.checked) {
div.style.backgroundColor = 'red';
}
}
<div id="CLWarn">Warning Colour</div>
<input type="radio" name="IM" id="a" value="1" onchange="changeColour(this)" />
<input type="radio" name="IM" id="b" value="1" onchange="changeColour(this)" />
Use checkbox instead radio:
<div id="CLWarn">Warning Colour </div>
<input type="checkbox" name="IM1" id="IM1" class="chk" />
<input type="checkbox" name="IM2" id="IM2" class="chk" />
and use jquery to archieve this:
$(document).ready(function(){
$(".chk").change(function(){
var im1 = $("#IM1");
var im2 = $("#IM1");
if ($("#IM1").is(':checked') && $("#IM2").is(':checked')){
$("#CLWarn").css("background-color", "green");
$("#CLWarn").css("line-height", "1.8rem");
}
})
})
Fiddle
Addictionally you can puy all your css in a separate class and set with addClass
$("#CLWarn").addClass("myClass");

Possible to add CSS to some JS to style disabled checkbox text

I'm using a bit of JS to limit the amount of checkboxes that a user can select in a form I am working on. With this JS, once the limit of 2 is reached, the remaining checkboxes are greyed out.
However, I am using other JS that removes the actual checkbox so that I can style the form anyway I like, so now when the limit is reached, there is no visual cue that the remaining choices cannot be selected.
I am hoping there is a way to style the text in the remaining choices to grey out when the limit of choices is reached.
Here is the JS I am using that greys out the checkboxes. Can I add a css style to this to do what I need?
$('input:checkbox[name="board_colors[]"]').on('change', function () {
var nightLifeLimit = $('input:checkbox[name="board_colors[]"]:checked').length;
if (nightLifeLimit == 2) {
$('input:checkbox[name="board_colors[]"]').each(function () {
if ($(this).is(':checked')) {
return;
}
else {
$(this).prop('disabled', true);
}
});
}
else {
$('input:checkbox[name="board_colors[]"]').each(function () {
$(this).prop('disabled', false);
});
}
});
HTML for the checkbox section of the form
<fieldset>
<legend>Choose color(s) <small class="fineprint">*choose up to two</small></legend>
<ul>
<li><input type="checkbox" class="checkbox" id="bright_green" value="Bright Green" name="board_colors[]" title="Please choose a color(s)" required minlength="1">
<label for="bright_green">Bright Green</label></li>
<li><input type="checkbox" class="checkbox" id="teal_blue" value="Teal Blue" name="board_colors[]">
<label for="teal_blue">Teal Blue</label></li>
<li><input type="checkbox" class="checkbox" id="sea_blue" value="Sea Blue" name="board_colors[]">
<label for="sea_blue">Sea Blue</label></li>
<li><input type="checkbox" class="checkbox" id="purple" value="Purple" name="board_colors[]">
<label for="purple">Purple</label></li>
<li><input type="checkbox" class="checkbox" id="magenta_dark_pink" value="Magenta Dark Pink" name="board_colors[]">
<label for="magenta_dark_pink">Magenta/Dark Pink</label></li>
<li><input type="checkbox" class="checkbox" id="watermelon_red" value="Watermelon Red" name="board_colors[]">
<label for="watermelon_red">Watermelon Red</label></li>
<li><input type="checkbox" class="checkbox" id="true_red" value="True Red" name="board_colors[]">
<label for="true_red">True Red</label></li>
<li><input type="checkbox" class="checkbox" id="orange" value="Orange" name="board_colors[]">
<label for="orange">Orange</label></li>
</ul>
<span><label for="board_colors[]" class="error"></label></span>
</fieldset>
I'd personally suggest adding a class to the parent <li> element and then styling the text of the <label> using CSS:
$('input:checkbox[name="board_colors[]"]').on('change', function () {
// cache your inputs for repeated access:
var inputs = $('input[type="checkbox"][name="board_colors[]"]'),
// using the cached jQuery object, filtering for the :checked elements:
nightLifeLimit = inputs.filter(':checked').length;
// iterating over each of the elements:
inputs.each(function () {
// 'this' is the current input:
$(this)
// disabling if it's not checked *and* if the limit is reached:
.prop('disabled', !this.checked && nightLifeLimit == 2)
// moving to the closest 'li' ancestor:
.closest('li')
// adding the class if the checkbox is disabled, removing if not:
.toggleClass('disabled', this.disabled);
});
});
JS Fiddle demo.
That said, if you move the <input /> elements before the <label> elements, giving:
<fieldset>
<legend>Choose color(s) <small class="fineprint">*choose up to two</small></legend>
<ul>
<li>
<input type="checkbox" class="checkbox" id="bright_green" value="Bright Green" name="board_colors[]" title="Please choose a color(s)" required="" minlength="1" />
<label for="bright_green">Bright Green</label>
</li>
<!-- others removed for brevity -->
</ul> <span><label for="board_colors[]" class="error"></label></span>
</fieldset>
You could simply use CSS to style the sibling <label> elements:
input[type=checkbox]:disabled + label {
color: #ccc;
}
JS Fiddle demo.
References:
closest().
each().
filter().
toggleClass().
One solution is you set a class to parent element that tells us that the amount of maximum allowable item is selected.
Then apply with css gray text. Example code
CSS
.max-element input:not(:checked) + label {color: lightgray;}
SJ
$('input:checkbox[name="board_colors[]"]').change(function () {
var nightLifeLimit = $('input:checkbox[name="board_colors[]"]:checked').length;
if (nightLifeLimit > 1) {
$('input:checkbox[name="board_colors[]"]').each(function () {
$(this).is(':checked') ? null : $(this).prop("disabled", true);
});
$(this).closest('ul').addClass('max-element');
}
else {
$('input:checkbox[name="board_colors[]"]').prop('disabled', false);
$(this).closest('ul').removeClass('max-element');
}
});
Note: Attribute minlength not allowed on element input. You can use data-minlength="1".

jQuery: How would I show/hide these elements?

Here's my HTML:
<ul>
<li>
<p><label><input type="checkbox" name="permission" value="1" class="permission_check" checked> Joe Schmoe</label></p>
<p class="radio_option"><label><input type="radio" name="viewpromote" value="1"> View and Promote</label></p>
<p class="radio_option"><label><input type="radio" name="createedit" value="1" checked> ...plus Create and Edit</label></p>
</li>
<li>
<p><label><input type="checkbox" name="permission" value="1" class="permission_check" checked> Bob Smith</label></p>
<p class="radio_option"><label><input type="radio" name="viewpromote" value="1" checked> View and Promote</label></p>
<p class="radio_option"><label><input type="radio" name="createedit" value="1"> ...plus Create and Edit</label></p>
</li>
</ul>
What I need to do is when a user checks/unchecks the permission_check input, then it should show/hide the radio_option elements for that list item.
$('.permission_check').change(function(){
$(this).closest('li').find('.radio_option').toggle(this.checked);
}).change();
Calling change() will trigger the callback once when the code is loaded to initialize the visibility correctly.
DEMO
Reference: change, closest, find, toggle
$('input[type="checkbox"]').change(function() {
$(this).closest('li').find('input[type="radio"]').toggle($(this).is(':checked'));
});
$(".permission_check").change(function() {
var $options = $(this).parents("li").find("p.radio_option");
if ($(this).is(":checked")) {
$options.show();
}
else {
$options.hide();
}
}
something like that:
$('.permission_check').change(function(){
$(this).parents('li').find('.radio_option').toggle();
});
Add the ID attributes to the radio button and then
Using Javascript, you can do:
function showhideOnClick() {
if(permission == true)
document.getElementById("radioControlID").style.display = "none";
else
document.getElementById("radioControlID").style.display = "block";
}

Categories