jQuery: How would I show/hide these elements? - javascript

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";
}

Related

How can I change style of parent elements of checked checkboxes

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>

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

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".

close other div when div1 is show and duplicate code pb jquery

I have 2 problems
1.First i need to allow only one div open , so when div question1 is show
div question2 and all other should hide, actually its not case in my poor code :).
2.Second problem , I achieve to made a code with an addclass when "is checked", but actually i duplicate all the code for each div .. Perhaps someone have a better elegant option to merge the code and avoiding duplicate code..
$(".checkbox").hide();
$(".question").show();
$('.question').click(function(){
$(".checkbox").toggle(10);
});
$('#test').change(function(){
if($(' input[type=checkbox]:checked').length) {
$('div.question').addClass("question-active");
} else {
$('div.question').removeClass("question-active");
}
});
$(".checkbox2").hide();
$(".question2").show();
$('.question2').click(function(){
$(".checkbox2").toggle(10);
});
$('#test2').change(function(){
if($(' input[type=checkbox]:checked').length) {
$('div.question2').addClass("question-active");
} else {
$('div.question2').removeClass("question-active");
}
});
Here is my code : http://jsfiddle.net/5C3p9/3/
Thanks for help
Regards
If you want to keep your HTML markup as it is, this should work:
// The ^= selector is used to select the elements which have the
// property starting with the text provided.
// ie: class starting with checkbox
$("div[class^='checkbox']").hide();
$("div[class^='question']").show();
$("div[class^='question']").click(function () {
// This way you are able to close the clicked one itself
$("div[class^='checkbox']").not($(this).next()).hide();
$(this).next("div[class^='checkbox']").toggle(10);
});
$("ul[id^='test']").change(function () {
// You can use the .toggleClass() method giving the class name
// and a boolean (add/remove) as parameters
$(this)
.parents()
.prev("div[class^='question']")
.toggleClass("question-active", $("input[type='checkbox']:checked").length != 0);
});
Demo: http://jsfiddle.net/5C3p9/7/
EDIT: I've put some comments in the code.
Some minor dom changes
<div class="quest question"></div>
<div class="ans checkbox">
<ul id="test">
<li>
<input type="checkbox" name="question-1" value="1"
/> is it vegetables ?
</li>
<li>
<input type="checkbox" name="question-2" value="2"
/> is it melon ?
</li>
</ul>
</div>
<div class="quest question2"></div>
<div class="ans checkbox2">
<ul id="test2">
<li>
<input type="checkbox" name="question-1" value="1"
/> is it vegetables ?
</li>
<li>
<input type="checkbox" name="question-2" value="2"
/> is it melon ?
</li>
</ul>
</div>
then
$(".quest").show();
$(".ans").hide();
$('.quest').click(function(){
$(this).next().toggle(10);
});
$('.ans').change(function(){
var $ans = $(this).closest('.ans');
$ans.prev().toggleClass('question-active', $ans.find('input:checkbox:checked').length > 0)
});
Demo: Fiddle
I made some modifications to your code. What I did is that I added some HTML-classes and made the javascript more general and traverse the HTML instead of pointing straight to the element.
Here's the jsFiddle: http://jsfiddle.net/E595w/1/
The new HTML:
<div class="question"></div>
<div class="checkbox">
<ul id="test" class="test">
<li>
<input type="checkbox" name="question-1" value="1"> is it vegetables ?
</li>
<li>
<input type="checkbox" name="question-2" value="2"> is it melon ?
<li>
</ul>
</div>
<div class="question"></div>
<div class="checkbox">
<ul id="test2" class="test">
<li>
<input type="checkbox" name="question-1" value="1"> is it vegetables ?
</li>
<li>
<input type="checkbox" name="question-2" value="2"> is it melon ?
<li>
</ul>
</div>
And here's the resulting Javascript:
$(".checkbox").hide();
$(".question").show();
$('.question').click(function(){
$('.checkbox').hide();
$(this).next(".checkbox").toggle(10);
});
$('.test').change(function(){
if($(' input[type=checkbox]:checked').length) {
$(this).parents('.checkbox').prev('div.question').addClass("question-active");
} else {
$(this).parents('.checkbox').prev('div.question').removeClass("question-active");
}
});
EDIT: Updated with code to answer your #1 question. See updated link to jsFiddle.
put to all your questions same class .question
if you want to differentiate between questions, use ids instead
also, put to to all answers container .checkbox
then use this function which will work for questions , no matter how many you have
$('.question').click(function(){
$(".checkbox").hide();
$(this).next(".checkbox").show(10);
});

How do you check if a radio button has the attribute 'checked' with Prototype

I have a bit of code that checks a list if LI tags which contain radio button input's. I have some clever logic via the Chocolate Chip Javascript framework library to work out when an LI is clicked, it will apply a relevant class to display the radio button has been selected.
However, I want to expand that logic so that it digs deeper into the LI and finds which radio button input is the one that is already selected (prior to any user choosing anything) when the page loads and apply a class to it so that it instantly highlights what is already selected.
I'm a bit new to Prototype so I'm not sure what is the best approach to do this so would appreciate any help you can offer.
So in the case below, I want to pick out button 3.
JSFiddle Link: http://jsfiddle.net/Qw6KA/
HTML:
<ul class="radioList">
<li>
<input type="radio" id="radio1" name="radioButton" value="Button 1">
<label for="radio1">Button 1</label>
</li>
<li>
<input type="radio" id="radio2" name="radioButton" value="Button 2">
<label for="radio2">Button 2</label>
</li>
<li>
<input type="radio" id="radio3" name="radioButton" value="Button 3" checked="checked">
<label for="radio3">Button 3</label>
</li>
<li>
<input type="radio" id="radio4" name="radioButton" value="Button 4">
<label for="radio4">Button 4</label>
</li>
</ul>
JS (Prototype):
$.RadioButtons = function( viewSelector, callback ) {
var items = viewSelector + ".radioList li";
var radioButtons = $$(items);
radioButtons.forEach(function(item) {
item.bind("click", function() {
radioButtons.forEach(function(check) {
check.removeClass("selected");
});
this.addClass("selected");
this.last().checked = true;
if (callback) {
callback(item);
}
});
});
};
Thanks
-JaXL
$.RadioButtons = function( viewSelector, callback ) {
var items = viewSelector + ".radioList li";
var radioButtons = $$(items);
radioButtons.forEach(function(item) {
item.bind("click", function() {
radioButtons.forEach(function(check) {
check.removeClass("selected");
});
this.addClass("selected");
this.last().checked = true;
if (callback) {
callback(item);
}
});
// Add this bit
if (item.select('input[checked]').length) {
item.addClassName('selected');
}
});
};

Categories