Select a checkbox that selects other checkboxes - javascript

I'm building out a simple user role management UI that has multiple permissions based on RBAC rules.
So I have lets say a group called users and inside of that group you get "add user", "edit users", "delete users" and "view users".
What I want to do is be able to select the entire "users" group checkbox and it should select the children checkboxes that belong to it, and so on. I have around 20 of these permissions groups.
I have looked around in stack overflow but am unable to find the solution or come up with something that works.
I'm looking for some help with either Javascript or Jquery.
I have included a screenshot to show you guys what I mean.
I don't have any JS code to show because I'm not even sure where to start.
I'm building the HTML view with Blade which is Laravel's templating engine. Here is my HTML so far.
#foreach($permissions as $name => $permission)
<div class="col-sm-3">
<h4>
<label>
<input type="checkbox">
{{ $name }}
</label>
</h4>
#foreach($permission as $item)
<div class="checkbox small">
<label>
<input name="permissions[]" value="{{ $item }}" type="checkbox">
{{ $item }}
</label>
</div>
#endforeach
</div>
#endforeach

Add appropriate classes to your parent elements and to your child elements so your code could be altered like in the below example.
#foreach($permissions as $name => $permission)
<div class="col-sm-3">
<h4>
<label>
<input type="checkbox" class="{{ $name }}">
{{ $name }}
</label>
</h4>
#foreach($permission as $item)
<div class="checkbox small">
<label>
<input name="permissions[]" class="{{ $name }}-child" value="{{ $item }}" type="checkbox">
{{ $item }}
</label>
</div>
#endforeach
</div>
#endforeach
Your HTML will become like this regarding class names.
users<input class="users" type="checkbox" />
<br><br>
<input class="users-child" type="checkbox" />
<input class="users-child" type="checkbox" />
<input class="users-child" type="checkbox" />
<input class="users-child" type="checkbox" />
<input class="users-child" type="checkbox" />
<input class="users-child" type="checkbox" />
Finally your jQuery part
$(".users").on("click",function(){ // use the same code for user-roles
var parentClassName = $(this).get(0).className;
if($(this).is(":checked")) {
$("."+parentClassName+"-child").each(function(key,value){
if($(value).get(0).checked==false) {
$(value).get(0).checked = true;
}
});
} else {
$("."+parentClassName+"-child").each(function(key,value){
$(value).get(0).checked = false;
});
}
});
A small example of the above you can check in jsFiddle

try code:
$(function(){
$(document).on('click','.col-sm-3 > h4 > label > input',function(){
var tag = $(this).prop('checked');
$(this).parents('.col-sm-3').find('.checkbox > label > input').prop('checked',tag);
});
})
if code after render template:
$(document).on('click','.col-sm-3 > h4 > label > input',func)
can replace with
$('.col-sm-3 > h4 > label > input').click(func)

Your code is just fine but to make the answer even smaller I would like you to assign class attribute to your main div and checkbox so out jquery will depend on our own classes/selector instead of bootstrap classes.
<div class="col-sm-3 permission-block">
<h4>
<label>
<input type="checkbox" class="something">
{{ $name }}
</label>
</h4>
and then your can add jQuery something like this.
$(document).ready(function(){
$(".something").on("click", function() {
var checked = $(this).is(":checked");
$(this).parent(".permission-block").children(".checkbox").find("input[type='checkbox']").props("checked", checked);
})
})

Related

How can I make show/hide div when radiobutton is checked or not, not only when I click it, but also when I call the data (check mark) from database

I have this Javascript code:
$(document).ready(function(){
$('input[type="radio"]').click(function(){
if($(this).attr("id")=="pindah1"){
$(".boxl").not(".pindah1").hide();
$(".pindah1").show();
}
if($(this).attr("id")=="pindah2"){
$(".boxl").not(".pindah2").hide();
$(".pindah2").show();
}
});
});
and this is my div which I want to show and hide whenever there's check mark on my radio button:
<div class="form-group">
<label>Apakah Sudah Pernah Pindah Pekerjaan?</label><br>
<div class="radio">
<label>
<input type="radio" name="pernahpindah" id = "pindah1" <?php if ($pernahpindah == 'Sudah Pernah') echo 'checked="checked"';?> value="pindah1"> Sudah Pernah<br />
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="pernahpindah" id = "pindah2"<?php if ($pernahpindah == 'Belum Pernah') echo 'checked="checked"';?> value="pindah2"> Belum Pernah <br /><br/>
</label>
</div>
</div>
<div class="pindah1 boxl">
<label>Nama Perusahaan Pertama</label>
<input class="form-control" name="perusahaanpertama" type="text" value="<?php echo $row['perusahaanpertama']; ?>"/><br />
</div>
</div>
which is work very well.
The problem is when I save the data into database and when I want to edit again based on the data that stored in database before, the check mark remain on my radio button but the div didn't show, so I have to click on it again to make it appear
Don't use jQuery for that. You already have the value from the database server side, so just set the style of the div by checking the variable in PHP that you have got out of the DB. (or set a CSS class with display:none on it and just add that class to the div).
As per http://api.jquery.com/hide/ using .hide and .show in jQuery are the equivalent of CSS display:none and display:block respectively.
<?
$showDiv = 0; // lets assume I got 0 out of the db and stored in this variable ?>
<div class="form-group">
<label>Apakah Sudah Pernah Pindah Pekerjaan?</label><br>
<div class="radio">
<label>
<input type="radio" name="pernahpindah" id = "pindah1" <?= ($pernahpindah === 'Sudah Pernah' ? 'checked="checked"' :''); ?> value="pindah1"> Sudah Pernah<br />
</label>
</div>
<div class="radio">
<label>
<input type="radio" name="pernahpindah" id = "pindah2"<?= ($pernahpindah === 'Belum Pernah' ? 'checked="checked"' :'');?> value="pindah2"> Belum Pernah <br /><br/>
</label>
</div>
</div>
<div class="pindah1 boxl"<?= ($showDiv ? " style='display:none'":""); ?>> <? // Set the display on the DIV here based on the database value ?>
<label>Nama Perusahaan Pertama</label>
<input class="form-control" name="perusahaanpertama" type="text" value="<?php echo $row['perusahaanpertama']; ?>"/><br />
</div>
</div>

Radio Buttons Hide / Show everything

i have a field with Radio Buttons: Hide and Show, I want when Hide is selected to hide all fields below and to display all when Show is selected. Below is my code:
<div id="product-options-wrapper" class="product-options">
<dd>
<div class="input-box display">
<ul class="options-list">
<li>
<input class="radio product-custom-option" type="radio" checked="checked"><label for="options_6032_2">Show</label>
</li>
<li>
<input class="radio product-custom-option" type="radio"><label for="options_6032_3">Hide</label>
</li>
</ul>
</div>
</dd>
<dd>
<div class="input-box fontclass">
<select>
<option>Arial </option>
<option>Lato </option>
<option>Disney Print </option>
</select>
</div>
</dd>
<dd>
<div class="input-box">
<input id="mirror" type="text" value="">
</div>
</dd>
<dd class="last">
<div class="colorclass">
<select>
<option>red </option>
<option>black </option>
</select>
</div>
</dd>
</div>
Update:
Radio Buttons don't have a fixed ID or class, the only stable thing in that radio buttons is the text.
Update:
I am almost there i use div:contains function and siblings, the function is work to hide but I don't know why is not work to show again. This is the jquery:
jQuery('div:contains("Hide ")').on('click', function(){
jQuery(this).closest('dd').siblings().hide();
});
jQuery('div:contains("Show ")').on('click', function(){
jQuery(this).closest('dd').siblings().show();
});
this is my html:
<li>
<input id="options_6032_2" class="radio validate-one-required-by-name product-custom-option" type="radio" price="0" value="42978" name="options[6032]" onclick="opConfig.reloadPrice()" checked="checked">
<span class="label">
<label for="options_6032_2">Hide </label>
</span>
</li>
<li>
<input id="options_6032_3" class="radio validate-one-required-by-name product-custom-option" type="radio" price="100" value="42979" name="options[6032]" onclick="opConfig.reloadPrice()">
<span class="label">
<label for="options_6032_3">
Show
<span class="price-notice">
+
<span class="price">Dkr100.00</span>
</span>
</label>
</span>
</li>
Update:
Maybe this will help, this code is the php code that generate this radio options:
$selectHtml = '<ul id="options-'.$_option->getId().'-list" class="options-list">';
$require = ($_option->getIsRequire()) ? ' validate-one-required-by-name' : '';
$arraySign = '';
switch ($_option->getType()) {
case Mage_Catalog_Model_Product_Option::OPTION_TYPE_RADIO:
$type = 'radio';
$class = 'radio';
if (!$_option->getIsRequire()) {
$selectHtml .= '<li><input type="radio" id="mylabel options_' . $_option->getId() . '" class="'
. $class . ' product-custom-option" name="options[' . $_option->getId() . ']"'
. ($this->getSkipJsReloadPrice() ? '' : ' onclick="opConfig.reloadPrice()"')
. ' value="" checked="checked" /><span class="label"><label for="options_'
. $_option->getId() . '">' . $this->__('None') . '</label></span></li>';
}
break;
case Mage_Catalog_Model_Product_Option::OPTION_TYPE_CHECKBOX:
$type = 'checkbox';
$class = 'checkbox';
$arraySign = '[]';
break;
}
Hiding and showing elements with jQuery/JavaScript is very straightforward. Add a class to the elements you wish to hide (in my example below I have named it hidden), then use the hide and show functions as follows:
$('#options_6032_3').click(function() {
$('.hidden').hide();
})
$('#options_6032_2').click(function() {
$('.hidden').show();
})
Check out this jsfiddle to see how it works.
EDIT
Based on the example you have provided in the comments to this answer, this alternative should work:
var hideRadio = $('li:nth-child(2) input:radio');
var showRadio = $('li:first input:radio');
hideRadio.click(function() {
$(this).closest('dd').siblings(':nth-child(3)').hide();
$(this).closest('dd').siblings(':nth-child(4)').hide();
})
showRadio.click(function() {
$(this).closest('dd').siblings(':nth-child(3)').show();
$(this).closest('dd').siblings(':nth-child(4)').show();
})
Check out this jsfiddle to see how it works.
NOTE:
Your dynamically created HTML code will need to be generated in the same format each time (with the dd and dt tags your most recent code contains).
if($('#radio').is(':checked')) { alert("it's checked"); }
Why don't you add class fields to the <dd> you want to hide and use jQuery or something similar to hide the <dd>. You may also want an identifier like a class or id to the radio buttons. Then you can hide the fields this way.
$(".show").change(function() {
if(this.checked) {
$(".fields").show();
}
});
$(".hide").change(function() {
if(this.checked) {
$(".fields").hide();
}
});
Here's a working fiddle: https://jsfiddle.net/28nboav9/
Is this similar to what you where looking for?
wrap your html code inside the div which need to be show/hide for better code optimization
HTML
<div id="product-options-wrapper" class="product-options">
<dd>
<div class="input-box display">
<ul id="options-6032-list" class="options-list">
<li>
<input id="options_6032_2" class="radio validate-one-required-by-name product-custom-option" type="radio" value="42978" name="options[6032]" onclick="opConfig.reloadPrice()" checked="checked"><label for="options_6032_2">Show </label>
</li>
<li>
<input id="options_6032_3" class="radio validate-one-required-by-name product-custom-option" type="radio" value="42979" name="options[6032]" onclick="opConfig.reloadPrice()"><label for="options_6032_3">Hide</label>
</li>
</ul>
</div>
</dd>
<div id="toggleVisibility"> //wrapped inside div
<dd>
<div class="input-box fontclass">
<select id="select_6031" class="required-entry product-custom-option form-control" onchange="opConfig.reloadPrice()" title="" name="options[6031]">
<option price="0" value="42969">Arial </option>
<option price="0" value="42970">Lato </option>
<option price="0" value="42971">Disney Print </option>
</select>
</div>
</dd>
<dd>
<div class="input-box">
<input id="options_6030_text mirror" class="input-text required-entry validate-length maximum-length-25 product-custom-option form-control" type="text" value="" name="options[6030]" onchange="opConfig.reloadPrice()">
</div>
</dd>
<dd class="last">
<div class="input-box colorclass">
<select id="select_6028" class="required-entry product-custom-option form-control" onchange="opConfig.reloadPrice()" title="" name="options[6028]">
<option price="0" value="42965">red </option>
<option price="0" value="42966">black </option>
</select>
</div>
</dd>
</div>
</div>
Please add this script into your page/js file
Jquery
$(document).ready(function () {
var $div=$('#toggleVisibility');
$('#options_6032_2').click(function () {
if ($(this).is(':checked')) {
$div.show();
}
})
$('#options_6032_3').click(function () {
if ($(this).is(':checked')) {
$div.show();
}
})
});
Try something like this. It finds the radio's parent DD and hides all it's siblings:
$('#options_6032_2').on('click', function(){
$(this).closest('dd').siblings().show();
});
$('#options_6032_3').on('click', function(){
$(this).closest('dd').siblings().hide();
});
It al depends a bit how dynamic your radio's are build up. You might want to assign a specific class for the selector.
Also see this fiddle: https://jsfiddle.net/cp5ses3y/
This should work
opConfig.reloadPrice = function(show){
if(show){
$('#select_6028,#options_6030_text,#select_6031').show();
}else{
$('#select_6028,#options_6030_text,#select_6031').hide();
}
}
You can change the selector to hide/show whatever you want. The best way I think, is to add a class to all the field you want to hide/show so you will only do $('.classToHideShow').show()
Here is the code with the modification : https://jsfiddle.net/55mrk3xf/
$("#hide").click(function() {
$('div.fontclass').hide();
$('div').children('#mirror').hide();
$('div.colorclass').hide();
});
$("#show").click(function() {
$('div.fontclass').show();
$('div').children('#mirror').show();
$('div.colorclass').show();
});
Try this. It uses a combination of JQuery and relative selectors to achieve the effect you want. Fiddle: https://jsfiddle.net/ut6jc4vp

jQuery show/hide a specific div with a checkbox

OK, I have an issue with some code and I'm really not sure how to code the outcome that I want to achieve.
I'm working on a site using Laravel 5.2 and I'm having an issue with hiding and showing specific divs based on the status of a checkbox. These are in a #foreach loop but I'm fairly sure that the laravel/#foreach isn't the issue, it's my lack of jQuery experience.
So here's some code.
#foreach ($event->extras()->get() as $extra)
<p>{{ $extra->name }}</p>
<p>{{ $extra->cost }}</p>
<p><input type="checkbox" name="extra-checkbox" id="extra-checkbox" value=""></p>
<div id="extra-info">
#if ($extra->infoRequired == "1")
<input type="text" name="extra-info-text" class="form-control">
#endif
</div>
#endforeach
The issue I'm having is that the $extra variable ID's ($extra->id) in the loop could be very different so a for-loop in the javascript is out. Each checkbox needs to show/hide only the specific "extra-info" div it is associated with.
How do I modify the following code to make it work for each individual $extra independently? I've considered putting the $extra->id into the class or div id but I can't figure out how to then implement it in the javascript.
$(document).ready(function() {
$('#extra-checkbox').change(function() {
if(this.checked)
$('#extra-info').fadeIn('fast');
else
$('#extra-info').fadeOut('fast');
Edit
I've added an id to the html as it's omission was my copying error. The issue I need to get my head around is that there will be multiple checkboxes (they're actually in a table, not <p>, but I was trying to make the code readable). Each checkbox is associated with an $extra and each $extra has it's own div that needs to be shown when the checkbox is checked.
There are a few mistakes in your code.
You cannot duplicate id values. You are doing it. Change it class.
Don't put <input /> inside <p>, instead, wrap it inside <label>.
Using $('#extra-checkbox') doesn't work, because it is name not id. Use $('[name="extra-checkbox"]').
This can be done using CSS itself. See below.
See the working example here:
input[name="extra-checkbox"] + input[name="extra-info-text"] {display: none;}
input[name="extra-checkbox"]:checked + input[name="extra-info-text"] {display: inline;}
<div class="entry">
<p>Name 1</p>
<p>Cost 1</p>
<div class="form-stuff">
<input type="checkbox" name="extra-checkbox" value="">
<input type="text" name="extra-info-text" class="form-control">
</div>
</div>
<div class="entry">
<p>Name 2</p>
<p>Cost 2</p>
<div class="form-stuff">
<input type="checkbox" name="extra-checkbox" value="">
<input type="text" name="extra-info-text" class="form-control">
</div>
</div>
<div class="entry">
<p>Name 3</p>
<p>Cost 3</p>
<div class="form-stuff">
<input type="checkbox" name="extra-checkbox" value="">
<input type="text" name="extra-info-text" class="form-control">
</div>
</div>
<div class="entry">
<p>Name 4</p>
<p>Cost 4</p>
<div class="form-stuff">
<input type="checkbox" name="extra-checkbox" value="">
<input type="text" name="extra-info-text" class="form-control">
</div>
</div>
You don't need jQuery or JavaScript for this.
You don't have input with id extra-checkbox, try this:
$('input[name="extra-checkbox"]').change(function() {
if(this.checked) {
$('#extra-info').fadeIn('fast');
} else {
$('#extra-info').fadeOut('fast');
}
});
or use a class since you should not have more then one element with same id.
Use pusedo selctors to get if checkbox is checked or not
$(document).ready(function() {
$('#extra-checkbox').change(function() {
if($(this).is(":checked"){ //Return true/false
$('#extra-info').fadeIn('fast');
}
else{
$('#extra-info').fadeOut('fast');
}
})
EDIT AFTER COMMENTS
You can use which is prefix selector, which mean if any id which start with extra_checkbox will respond to this snippet.
$('div[id^="extra-checkbox"]')
For more information visit HERE
NOTE: id need to be unique as per W3C standard
You are adding the same id to multiple divs, this is bad. You need to add a unique id or a unique data attribute to every element and reference it in you change event.
Also:
$('#extra-checkbox')
should be this:
$('*[name="extra-checkbox"]')
This should work:
#foreach ($event->extras()->get() as $extra)
<p>{{ $extra->name }}</p>
<p>{{ $extra->cost }}</p>
<p><input type="checkbox" name="extra-checkbox" value="{{ $extra->name }}"></p>
<div class="extra-info" data-name="{{ $extra->name }}">
#if ($extra->infoRequired == "1")
<input type="text" name="extra-info-text" class="form-control">
#endif
</div>
#endforeach
then
$(document).ready(function() {
$('*[name="extra-checkbox"]').change(function() {
if($(this).prop('checked'))
$('.extra-info[data-name="'+$(this).data('name')+'"]').fadeIn('fast');
else
$('.extra-info[data-name="'+$(this).data('name')+'"]').fadeOut('fast');

bootstrap check/uncheck multiple elements with js

I am trying to make this work but can't make it happen. I have a bootstrap template and i want to check and uncheck multiple checkboxes (like this: http://jsfiddle.net/v6wmV/177/ )
I know this is a common subject with many solutions, but none seem to work for this case and i would like to know why.
This is the code snippet from the view:
<div class="hide" id="states">
<div class="control-group">
<label class="control-label">Select</label>
<div class="check">
<div class="controls">
<label class="checkbox line">
<input type="checkbox" class="all" value="Todas" id="allstates" name="st[25]"/>All
</label>
<label class="checkbox line">
<input type="checkbox" value="Caba" id="" name="st[1]"/>Ciudad Autónoma de Buenos Aires
</label>
<label class="checkbox line">
<input type="checkbox" value="Buenos Aires" id="" name="st[2]"/> Buenos Aires
</label>
<label class="checkbox line">
<input type="checkbox" value="Catamarca" id="" name="st[3]"/> Catamarca
</label>
<label class="checkbox line">
<input type="checkbox" value="Chaco" id="" name="st[4]"/> Chaco
</label>
</div>
</div>
</div>
</div>
and this is my js file (with other functions):
$('.hide').hide();
$('#registered').click(function(){
$('#content').toggle('fast');
});
$('#age').click(function () {
$('#content2').hide('fast');
$('#content1').show('fast');
});
$('#range').click(function () {
$('#content1').hide('fast');
$('#content2').show('fast');
});
$('#with').click(function(){
$('#child').toggle('fast');
});
$('#showstates').click(function(){
$('#states').show('fast');
});
$('#hidestates').click(function(){
$('#states').hide('fast');
});
//function for check/uncheck
$('.all').click(function() {
var $checkboxes = $(this).parent().find('input[type=checkbox]');
$checkboxes.prop('checked', $(this).is(':checked'));
});
this is the fiddle: http://jsfiddle.net/jimena/j56Dy/
which is not working
you need to go up two stages instead of one. parent() gives you the label element, you need to go up to the "controls"-classed div to apply your find method :
var $checkboxes = $(this).parent().parent().find('input[type=checkbox]');
Of course that was to apply minimal change to your code way. The one provided by Joe up here is probably smarter : getting all the checkboxes you want without having to use parent() method. But to do so you might want to id your checkbox group so that you do not select all the checkboxes accross your DOM.
By the way, don't you have to show your hide div at some point to see your checkboxes ?
Edit> OK actually Manish is right with parents it is just right, forget my answer :D

Create elements based on checkbox selection

I have this HTML:
<fieldset style="" title="Variaciones" id="product-create-step-3" class="fstep">
<legend>Variaciones</legend>
<section id="choices">
<input type="checkbox" value="24" id="24" name="Size"> Size
<input type="checkbox" value="25" id="25" name="Color"> Color
<section style="display: none" class="options_holder"></section>
<section style="display: none" class="variations_holder"></section></section>
</fieldset>
I need to create some input based on what checkbox/es was marked. For example if I mark first one 'Size' I should obtain this:
<section style="display: none" class="options_holder">
<input name="size[24][]" value="" placeholder="Write your size" />
</section>
if I mark second one 'Color' I should obtain this:
<section style="display: none" class="options_holder">
<input name="color[25][]" value="" placeholder="Write your color" />
</section>
if I mark both 'Size' & 'Color' I should obtain this:
<section style="display: none" class="options_holder">
<input name="size[24][]" value="" placeholder="Write your size" />
<input name="color[25][]" value="" placeholder="Write your color" />
</section>
How I would do that?
UPDATE 1
I'm trying to get which checkbox was checked by doing this:
$("#choices :checked").each(function() {
console.log(this.id + "was checked");
});
But it's not working
UPDATE 2
I realize into another problem, how I check when a checkbox was checked and after trigger some code without know any data of the checkbox? I have a code that generates check-boxes on the fly so I'll never know their name's or id's or any other data. My template for that creation looks like this:
<input type="checkbox" name="{{ entity.getLabel|lower }}" id="{{ entity.getLabel|lower ~ "_choice" }}" value="{{ entity.getId }}" /> {{ entity.getLabel }}
Where for example name could take "color" and in that case id will be "color_choice" or name could take "size" and in that case id will be "size_choice", sometimes one is created some time both are created. What I need to know and I don't is how to know which check-box was checked and when trigger some event as for example create some others input's on the fly. How do I deal with this part too?
So, your javascript should work if you change your selector to include the element that uses the pseudo-selector:
$("#choices input:checked").each(function() {
console.log(this.id + "was checked");
});
As for accessing the attribute values, you can use either the native javascript object that you're using, i.e.:
console.log("value is " + this.value);
Or you can use jQuery's attr()
console.log("name is " + $(this).attr('name'))
A working example showing both cases, as well as having attached the event to any click of input items is at this jsfiddle:
http://jsfiddle.net/k3B73/
<fieldset style="" title="Variaciones" id="product-create-step-3" class="fstep">
<legend>Variaciones</legend>
<section>
<input type="checkbox" value="24" id="24" name="Size" id='size_choice'> Size
<input type="checkbox" value="25" id="25" name="Color" id='color_choice'> Color
<section style="display: none" class="options_holder" id='options_holder'></section>
<section style="display: none" class="variations_holder"></section>
</section>
</fieldset>
<script type="text/javascript">
$(document).ready(function(){
$('#size_choice').click(function(){
if ($(this).is(':checked'))
$("#options_holder").append('<input name="size[24][]" value="" placeholder="Write your size" id="size" />');
else
$("#size").destroy();
});
$('#color_choice').click(function(){
if ($(this).is(':checked'))
$("#options_holder").append('<input name="color[25][]" value="" placeholder="Write your color" id="choice" />');
else
$("#color").destroy();
});
})
</script>

Categories

Resources