How can I show/hide divs with checkboxes and javascript? - javascript

I've seen several posts similar to what I'm looking for, but not quite my exact circumstance. I want to show/hide html divs when some check boxes are clicked.
I've found the following:
<script>
jQuery(function(){
var checks = $('#checkbox1, #checkbox2, #checkbox3');
checks.click(function(){
if (checks.filter(':checked').length == checks.length) {
$('#purchaseForm').show();
} else {
$('#purchaseForm').hide();
}
}).triggerHandler('click')
})
</script>
<label><input name="checkbox1" id="checkbox1" value="" type="checkbox"> checkbox1 </label>
<label><input name="checkbox2" id="checkbox2" value="" type="checkbox"> checkbox2 </label>
<label><input name="checkbox3" id="checkbox3" value="" type="checkbox"> checkbox3 </label>
<div id="purchaseForm">
Content Here
</div>
What I'm looking for is:
<label><input name="checkbox1" id="checkbox1" value="" type="checkbox"> checkbox1 </label>
<label><input name="checkbox2" id="checkbox2" value="" type="checkbox"> checkbox2 </label>
<label><input name="checkbox3" id="checkbox3" value="" type="checkbox"> checkbox3 </label>
<div id="A">
Display for selected Checkbox one only
</div>
<div id="B">
Display for selected Checkbox two only
</div>
<div id="C">
Display for selected Checkbox three only
</div>
<div id="D">
Display for selected Checkboxes one and two
</div>
<div id="E">
Display for selected Checkboxes one and three
</div>
<div id="F">
Display for selected Checkboxes two and three
</div>
<div id="G">
Display for selected Checkboxes one two and three
</div>
This helped me understand this a little bit more, but not everything. When all three checkboxes are clicked, the content appears. What I'm looking for is content based on the combinations of check boxes.
For example, say checkbox1 is selected, then only div-A would display. But if checkboxes 1 and 3 are both selected, then div-E would display, and I'm looking for that with each checkbox.
I'm still learning javascript so any advice would be greatly appreciated. Thanks!

$(document).ready(function() {
var map = {
0: '', 1: 'A', 2: 'B', 3: 'D',
4: 'C', 5: 'E', 6: 'F', 7: 'G'
};
$('#checkbox1, #checkbox2, #checkbox3').change(function(event) {
var bitmask = ($('#checkbox1')[0].checked?1:0)+
($('#checkbox2')[0].checked?2:0)+
($('#checkbox3')[0].checked?4:0);
$('div').hide();
$('div#'+map[bitmask]).show();
});
$('div').hide();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<label><input name="checkbox1" id="checkbox1" value="" type="checkbox"> checkbox1 </label>
<label><input name="checkbox2" id="checkbox2" value="" type="checkbox"> checkbox2 </label>
<label><input name="checkbox3" id="checkbox3" value="" type="checkbox"> checkbox3 </label>
<div id="A">
Display for selected Checkbox one only
</div>
<div id="B">
Display for selected Checkbox two only
</div>
<div id="C">
Display for selected Checkbox three only
</div>
<div id="D">
Display for selected Checkboxes one and two
</div>
<div id="E">
Display for selected Checkboxes one and three
</div>
<div id="F">
Display for selected Checkboxes two and three
</div>
<div id="G">
Display for selected Checkboxes one two and three
</div>

I would map the checkboxes to binary values, where checkbox1 = 1, checkbox2=2, checkbox3=4, checkbox4=8, etc. So, check if the box is checked or not, and if it is, add it's binary value to a number. When your done, analyze the number to determine what boxes are checked.
Here is a working codepen
HTML:
<label><input name="checkbox1" id="checkbox1" value="" type="checkbox"> checkbox1 </label>
<label><input name="checkbox2" id="checkbox2" value="" type="checkbox"> checkbox2 </label>
<label><input name="checkbox3" id="checkbox3" value="" type="checkbox"> checkbox3 </label>
<div id="content">
a
</div>
JS:
$('input').click(function() {
var number = checkCheckBoxes();
if(number == 0) {
$('#content').html("None of them!");
}
if(number == 1) {
$('#content').html("Just 1!");
}
if(number == 2) {
$('#content').html("Just 2!");
}
if(number == 3) {
$('#content').html("Just 1 & 2!");
}
if(number == 4) {
$('#content').html("Just 3!");
}
if(number == 5) {
$('#content').html("Just 1 & 3!");
}
if(number == 6) {
$('#content').html("Just 2 & 3!");
}
if(number == 7) {
$('#content').html("All of them!");
}
})
function checkCheckBoxes() {
var number = 0;
if($('#checkbox1:checked').length) {
number = number + 1;
}
if($('#checkbox2:checked').length) {
number = number + 2;
}
if($('#checkbox3:checked').length){
number = number + 4;
}
return number;
}

It's better if you manage the checkboxes with onchangeevent instead of click event:
checks.on('change', function(){
$(this).prop('checked') // true or false
});

Cleanest solution is to add the checkbox ids in the div itself and use it.
Use attribute contains selector to find the respective div. https://api.jquery.com/attribute-contains-selector/
Check the below code.
HTML
<label>
<input name="checkbox1" id="checkbox1" value="" type="checkbox"> checkbox1 </label>
<label>
<input name="checkbox2" id="checkbox2" value="" type="checkbox"> checkbox2 </label>
<label>
<input name="checkbox3" id="checkbox3" value="" type="checkbox"> checkbox3 </label>
<div id="A" checkboxids="checkbox1">
Display for selected Checkbox one only
</div>
<div id="B" checkboxids="checkbox2">
Display for selected Checkbox two only
</div>
<div id="C" checkboxids="checkbox3">
Display for selected Checkbox three only
</div>
<div id="D" checkboxids="checkbox1,checkbox2">
Display for selected Checkboxes one and two
</div>
<div id="E" checkboxids="checkbox1,checkbox3">
Display for selected Checkboxes one and three
</div>
<div id="F" checkboxids="checkbox2,checkbox3">
Display for selected Checkboxes two and three
</div>
<div id="G" checkboxids="checkbox1,checkbox2,checkbox3">
Display for selected Checkboxes one two and three
</div>
JS
$("div[checkboxids]").hide();
$("input:checkbox").click(function() {
// Hide all the div
$("div[checkboxids]").hide();
// Enable respective divs only
$("input:checked").each(function() {
$("div[checkboxids*='" + $(this).attr("id") + "']").show();
});
});
Demo : https://jsfiddle.net/qp2mLj99/4/

$(document).ready(function(){
$('#checkbox1').click(function(){
$("#purchaseForm").slideToggle('slow');
$("#purchaseForm").toggleClass('active');
});
});
This is easy and works very well. You can always change the slideToggle or toggleClass to show and hide.
Hope it helps you!

Related

If two radio button checked, add css to div

There are two radio buttons separately. Have different name values. I'm trying to add a css to the div element when both are "checked".
$(document).ready(function(){
$('input[name="nameone"]').click(function(){
if($(this).is(":checked")){
$(".calculate-total").css("display","block")
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
<input type="radio" name="nameone" /> Nameone radio
</label>
<br><br>
<label>
<input type="radio" name="nametwo" /> Namtwo radio
</label>
<div class="calculate-total" style="display:none;">If two radio checked both, this div will be visible.</div>
Just add a second if condition like you do for the input[name="nameone"]:
function showDiv() {
if ($('input[name="nameone"]').is(":checked") && $('input[name="nametwo"]').is(":checked")) {
$(".calculate-total").css("display", "block")
}
}
$(document).ready(function() {
$('input[name="nameone"], input[name="nametwo"]').click(function() {
showDiv();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
<input type="radio" name="nameone" /> Nameone radio
</label>
<br><br>
<label>
<input type="radio" name="nametwo" /> Namtwo radio
</label>
<div class="calculate-total" style="display:none;">If two radio checked both, this div will be visible.</div>
Just check if both of them are checked:
$(document).ready(function(){
$('input[name="nameone"], input[name="nametwo"]').click(function(){
if($('input[name="nameone"]').is(":checked") && $('input[name="nametwo"]').is(":checked")){
$(".calculate-total").css("display","block")
}
});
});
You are only checking if the first radio input is clicked (checked), that's why you the div is showing when you click on the first radio input. You should listen/check for both. If both are clicked (checked). Then that's when you want to do something. You can use the && to get the job done
function showDiv() {
if ($('input[name="nameone"]').is(":checked") && $('input[name="nametwo"]').is(":checked")) {
$(".calculate-total").css("display", "block")
}
}
$(document).ready(function() {
$('input[name="nameone"], input[name="nametwo"]').click(function() {
showDiv();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
<input type="radio" name="nameone" /> Nameone radio
</label>
<br><br>
<label>
<input type="radio" name="nametwo" /> Namtwo radio
</label>
<div class="calculate-total" style="display:none;">If two radio checked both, this div will be visible.</div>
You have to check if all radio buttons are checked and based on this check you can toggle the visibility of the block.
I added a class to the radiobuttons you want to check. And only if the length of all radiobuttons is equal to the checked onces i show the calculate-total div
$(document).ready(function() {
$('input[type="radio"]').on('change', function() {
if ($('.check-it').filter(':checked').length === $('.check-it').length) {
$(".calculate-total").css("display", "block")
} else {
$(".calculate-total").css("display", "none")
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
<input type="radio" name="nameone" class="check-it" /> Nameone radio
</label>
<label>
<input type="radio" name="nameone" /> Nameone radio
</label>
<br><br>
<label>
<input type="radio" name="nametwo" class="check-it" /> Namtwo radio
</label>
<label>
<input type="radio" name="nametwo" /> Namtwo radio
</label>
<div class="calculate-total" style="display:none;">If two radio checked both, this div will be visible.</div>
You need to listen for both radio buttons and check for both each time:
$(document).ready(function(){
$('input:radio').change(function(){
if($('input[name="nameone"]').is(":checked") && $('input[name="nametwo"]').is(":checked")){
$(".calculate-total").css("display","block")
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
<input type="radio" name="nameone" /> Nameone radio
</label>
<br><br>
<label>
<input type="radio" name="nametwo" /> Namtwo radio
</label>
<div class="calculate-total" style="display:none;">If two radio checked both, this div will be visible.</div>

Make check-boxes becoming one group of radio button

I cannot make the input name same or value same. The second and third inputs come from a loop using c# razor. I have 2 sets of radio inputs first one is one set and second and third are another set. Because the second and third have the same name, checking one makes the other unchecked. I want the same for all of them together so it would be like I have one set of 3 radio buttons. Like I said above I am not able to make the name or value same due to back-end data display issue. Here is my attempt below.
//first radio <br/>
<div class="radio">
<label>
<input id="dcenter-allradio" type="radio" value="0" />All
</label>
</div>
//this radio button is a loop <br>
<input type="radio" name="#Model.Facet.Key" value="#item.Key">tagitem.j
<div class="radio">
<label>
<input id="dcenter-listradio" type="radio" name="#Model.Facet.Key" value="#item.Key" />tagItem.Name
</label>
</div>
<script>
$(document).ready(function () {
if ($('#dcenter-listradio').prop("checked", true)) {
$('#dcenter-allradio').prop("checked", false);
}
if ($('#dcenter-allradio').prop("checked", true)) {
$('#dcenter-listradio').prop("checked", false);
}
});
</script>
If you can give them all the same class, then you can just use jQuery to detect when a change has occurred and then uncheck other items in the same class.
$(document).ready(function() {
var selector = ".groupTogether";
// or if you can't give same class, you could use "#unrelatedRadio, input[name='related']"
$(selector).change(function()
{
if(this.checked)
{
$(selector).not(this).prop('checked', false);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="unrelatedRadio" name="unrelated" type="radio" class="groupTogether">unrelated</input>
<input id="relatedA" name="related" type="radio" class="groupTogether">Related A</input>
<input id="relatedB" name="related" type="radio" class="groupTogether">Related B</input>
Or, if you can't give them the same class, just replace the selector with something that selects both sets (in my example, "#unrelatedRadio, input[name='related']")
let radios = document.querySelectorAll("input");
for (let i of radios){
i.name="same"
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
//first radio <br/>
<div class="radio">
<label>
<input id="dcenter-allradio" type="radio" value="0" />All
</label>
</div>
//this radio button is a loop <br>
<input type="radio" name="#Model.Facet.Key" value="#item.Key">tagitem.j
<div class="radio">
<label>
<input id="dcenter-listradio" type="radio" name="#Model.Facet.Key" value="#item.Key" />tagItem.Name
</label>
</div>

Make a checkbox unchecked when it is hidden using JavaScript

I have a JavaScript function in place for a multiple choice quiz:
If the answer is 'Yes' - (checked by a checkbox) - Then a sub-question will appear, but if the user clicks 'No' the sub-question won't appear.
JavaScript
$(document).ready(function() {
var par = $('#SQ1');
$(par).hide();
$('#Q1').click(function(e) {
$(par).slideToggle('slow');
});
});
$(document).ready(function(){
$('#Q1NO').click(function(){
$('#SQ1').hide('slow');
});
})
Questions checkboxes
<div>
<input type="checkbox" id="Q1" name="chk[]" value="Yes"> Yes</input>
<br>
<input type="checkbox" id="Q1NO" name="chk[]" value="No"> No</input>
</div>
Sub-Question checkboxes
<div id="SQ1">
<div>
<input type="checkbox" name="chk[]" value="Yes 2" id="Q1R"> Yes</input>
<br>
<input type="checkbox" name="chk[]" value="No 2"> No</input>
</div>
</div>
I am inputting the values from the checkboxes into a database and the problem is that if the user clicked 'Yes' and then selected a box from the sub-question, but then changed their mind and clicked 'No' on the primary question, the sub-question will disappear, but the box is still checked inside it and it gets added to the database - Which I don't want.
Is there a way to uncheck an item within a div, on the click of the 'No' from the first div?
Thanks for reading
Uncheck all subquestions checkboxes:
$('#Q1NO').click(function(){
$('#SQ1').hide('slow')
.find('input:checkbox').prop('checked',false);
});
First of all there either should be radio button for Yes/no or only one checkbox. There are several ways to achieve your requirement. I have posted below easiest one. See if it helps.
function showHideSub(isChecked){
if(isChecked)
{
$("#sub").show()
}
else
{
$("#sub").hide()
$("#sub input[type=checkbox]").removeAttr("checked");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div>
<input type="checkbox" id="Q1" name="chk[]" onclick="showHideSub(this.checked)" value="Yes"> Yes / No </input>
<br>
</div>
<div id="sub" style="display:none">
<input type="checkbox" name="chk[]" value="Yes 2" id="Q1R"> Yes/No</input>
</div>
Solution without loop as you can set properties on all query matches.
$('#Q1NO').click(function() {
par.hide('slow');
par.find("input[type=checkbox]").prop('checked', false);
});

Hide and Show radio buttons with checkbox

Basically i'd like hide and show the radio buttons if the checkbox is checked or not, but with some conditions.
The first radio button needs to be checked by default even if hidden once the checkbox has been checked.
If the checkbox has been checked then show all the radio buttons and the user can choose another radio button if necessary.
But, if the checkbox is unchecked, set the radio button back to the first checked by default and hide all the radio buttons.
I tried to modify some solutions that i found, but without success :(
My HTML:
<input name="featured_ad" value="1" type="checkbox">condition</input>
<div class="buttons">
<input type="radio" name="ad_pack_id" value="497649">value 1<br>
<input type="radio" name="ad_pack_id" value="497648">value 2<br>
<input type="radio" name="ad_pack_id" value="497647">value 3<br>
</div>
Thanks a lot!
As we discussed does this work for you?
HTML:
<input name="featured_ad" value="1" type="checkbox" onclick="resetradio(this)">condition
<div class="buttons">
<input type="radio" name="ad_pack_id" value="497649" onclick="setcheckbox()">value 1<br>
<input type="radio" name="ad_pack_id" value="497648" onclick="setcheckbox()">value 2<br>
<input type="radio" name="ad_pack_id" value="497647" onclick="setcheckbox()">value 3<br>
</div>
JS:
function resetradio (checkbox) {
var buttons = document.querySelector('.buttons');
var radios = document.getElementsByName('ad_pack_id');
radios[0].checked = true;
if (checkbox.checked == true) {
buttons.style.display = 'block';
}
else {
buttons.style.display = 'none';
}
}
function setcheckbox () {
var checkbox = document.getElementsByName('featured_ad')[0];
if (checkbox.checked == false) {
checkbox.checked = true;
}
}
CSS:
.buttons {
display: none;
}
Fiddle: http://jsfiddle.net/dgqn5fc4/1/
You've got a few issues here. First of all, you need to make sure you close your input tags:
<input name="featured_ad" value="1" type="checkbox">condition</input>
<div class="buttons">
<input type="radio" name="ad_pack_id" value="497649">value 1</input>
<input type="radio" name="ad_pack_id" value="497648">value 2</input>
<input type="radio" name="ad_pack_id" value="497647">value 3</input>
</div>
You can then check your default radio button right in the html by adding checked="checked" to the appropriate radio element.
<div class="buttons">
<input type="radio" checked="checked" name="ad_pack_id" value="497649">value 1</input>
<input type="radio" name="ad_pack_id" value="497648">value 2</input>
<input type="radio" name="ad_pack_id" value="497647">value 3</input>
</div>
You can hide your radio buttons by default in your CSS:
.buttons {
display: none;
}
Then, you can show them using jQuery, and do your selections based on your condition:
$(document).ready(function(){
$("input[name='featured_ad']").on("change", function(){
var isChecked = $(this).prop("checked");
if(isChecked){
$(".buttons").show();
} else {
$(".buttons").hide();
$("input[name='ad_pack_id'][value='497649']").prop("checked", "checked");
}
});
});
Edit:
Here is a fiddle: http://jsfiddle.net/8q94Lvbo/
Do the following.
$('[name="featured_ad"]').on('change', function(){
var $first = $('[name="ad_pack_id"]').first();
var $rest = $('[name="ad_pack_id"]').slice(1);
if( $(this).is(':checked') ){
$first.prop('checked',true);
$first
.closest('span')
.hide();
$rest.prop({
'checked':false,
'disabled':false
});
} else {
$first
.closest('span')
.show();
$first.prop('checked',true);
$rest.prop({
'checked':false,
'disabled':true
});
}
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input name="featured_ad" value="1" type="checkbox">condition
<div class="buttons">
<span><input type="radio" name="ad_pack_id" value="497649">value 1</span><br/>
<span><input type="radio" name="ad_pack_id" value="497648">value 2</span><br/>
<span><input type="radio" name="ad_pack_id" value="497647">value 3</span><br/>
</div>
You have to pass arguments to javaScript in quotes like onclick="Show_Div('Div_1')" not like onclick="Show_Div(Div_1)".
And for others requirement you can check the following html
<input type="checkbox" id="check" onclick="checkFun();"/>Your CheckBox<br/>
<img src="http://icons.iconarchive.com/icons/paomedia/small-n-flat/1024/flower-icon.png" alt="" onclick="Show_Div('Div_1')" width="100px">
<p>
<input id="radio1" type="radio" onclick="Show_Div('Div_1')" class="cb1" onchange="cbChange1(this)" checked="checked"/>Flower 1</p>
<div id="Div_1" style="display: none;">
Flower is pink.
</div>
<br/>
<br/>
<img src="http://www.clker.com/cliparts/0/d/w/v/V/p/pink-flower-md.png" alt="" onclick="Show_Div('Div_2')" width="100px">
<p>
<input type="radio" id="radio2" onclick="Show_Div('Div_2')" class="cb1" onchange="cbChange1(this)" disabled >Flower 2</p>
<div id="Div_2" style="display: none;">
Flower is orange.
</div>
You can apply following simple JS and jQuery to achive your goal
function checkFun(){
console.log("click");
var ch=$("#check");
if(ch.is(':checked')){
$("#radio2").attr("disabled",false);
}else{
$("#radio1").prop("checked", true);
$("#radio2").prop("checked", false);
$("#radio2").attr("disabled",true);
}
}
function Show_Div(Div_id) {
if(Div_id=="Div_1"){
$("#Div_1").show();
$("#Div_2").hide();
}else{
$("#Div_2").show();
$("#Div_1").hide();
}
}
function cbChange1(obj) {
var cb1 = document.getElementsByClassName("cb1");
for (var i = 0; i < cb1.length; i++) {
cb1[i].checked = false;
}
obj.checked = true;
}

display selected checkbox options on the page

was wondering if i could get a little help. I have 3 checkboxes and want to display the text before each checkbox back to the user.
<form id="extras" onchange="calculate()">
option 1<input type="checkbox" name="box" value="2000" id="snow" onchange="calculate()" checked><br>
option 2<input type="checkbox" name="box" value="500" id="water" onchange="calculate()" checked><br>
option 3<input type="checkbox" name="box" value="150" id="air" onchange="calculate()"><br><br>
</form>
so i can say you have selected option 1 and option 2 if they are both selected. Ive managed to to this for my dropdown using innerHTML but am unsure how to achieve this for the checkboxes. any ideas on how i can do this? thanks for any advice.
HTML
<form id="extras">
<label id="lbl_1">option 1</label><input type="checkbox" name="box" value="2000" id="1" onchange="calculate()"><br>
<label id="lbl_2">option 2</label><input id="2" type="checkbox" name="box" value="500" onchange="calculate()"><br>
<label id="lbl_3">option 3</label><input type="checkbox" name="box" value="150" id="3" onchange="calculate()"><br><br>
</form>
<span id="txt"></span>
Calculate function
function calculate()
{
document.getElementById("txt").innerHTML = "";
var checkBoxes = document.getElementsByName("box");
for(var i=0; i < checkBoxes.length;i++)
{
if(checkBoxes[i].checked)
{
document.getElementById("txt").innerHTML += document.getElementById("lbl_" checkBoxes[i].id).innerHTML
}
}
}
And JsFiddle
Here you go. I wrote this in jQuery, but you can convert it to vanilla JS.
http://jsfiddle.net/P2BfF/
Essentially you need to create labels for your checkboxes:
<label for='snow'>option 1</label>
Then based on checked, you can display the innerHTML of that element.
Here is my JS:
var checkboxes = $('#extras').find('input[type=checkbox]');
checkboxes.on('click',function() {
var selected = [];
checkboxes.each(function(idx,item) {
if (item.checked)
selected.push( $('label[for="' + item.id + '"]').html() );
});
return alert(selected);
});

Categories