show hide content depending if a checkbox is checked - javascript

I'm pretty new to jquery so I'm proud of myself for what I've figured out so far. What I'm trying to do is show/hide a list of options depending on the approprate check box status. Eveything is working just fine but I can't figure out how to check to see if a check box is checked on load I know I should be able to use is.checked right now I have this javascript
$('.wpbook_hidden').css({
'display': 'none'
});
$(':checkbox').change(function() {
var option = 'wpbook_option_' + $(this).attr('id');
if ($('.' + option).css('display') == 'none') {
$('.' + option).fadeIn();
}
else {
$('.' + option).fadeOut();
}
});
Which fades in and out a class depending on the status of the checkbox. This is my html
<input type="checkbox" id="set_1" checked> click to show text1
<p class = "wpbook_hidden wpbook_option_set_1"> This is option one</p>
<p class = "wpbook_hidden wpbook_option_set_1"> This is another option one</p>
<input type="checkbox" id="set_2"> click to show text1
<p class = "wpbook_hidden wpbook_option_set_2"> This is option two</p>
The two problems I have are that the content with the .wpbook_hidden class is always hidden and if the checkbox is checked on load the content should load.
If someone could figure out how to check the status of the box on load that would be much appriciated feel free to play with this jfiddle http://jsfiddle.net/MH8e4/3/

you can use :checked as a selector. like this,
alert($(':checkbox:checked').attr('id'));
updated fiddle
or if you want to check the state of a particular checkbox, it would be something like this
alert($('#set_1')[0].checked);
updated fiddle
for the comment below, I have edited your code and now looks like this.
$('.wpbook_hidden').hide();
$(':checkbox').change(function() {
changeCheck(this);
});
$(':checkbox:checked').each(function(){ // on page load, get the checked checkbox.
changeCheck(this); // apply function same as what is in .change()
});
function changeCheck(x) {
var option = 'wpbook_option_' + $(x).attr('id');
if ($('.' + option).is(':visible')) { // I'm not sure about my if here.
$('.' + option).fadeOut(); // if necessary try exchanging the fadeOut() and fadeIn()
}
else {
$('.' + option).fadeIn();
}
}
#updated fiddle

to checkout if a checkbox is checked you can use the following code :
$(':checkbox').change(function() {
if ( $(this).checked == true ){
//your code here
}
});

Try this:
$("input[type=checkbox]:checked").each(fun....

Related

Hide/Show div based on checkbox selection

I'm building a form that's supposed to hide and show content according to checkbox selections made by the user. No luck so far in identifying where the error in my code is. Any help will be appreciated. Thanks!
function documentFilter(trigger, target) {
$(trigger).change(function () {
if ($(trigger).checked)
$(target).show();
else
$(target).hide();
});
}
documentFilter("triggerDiv", "hideableDiv");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="checkbox" id="triggerDiv" > Some caption </label>
<div id="hideableDiv" class="well">
Some hidable content </div>
You were not sending the correct jQuery string to your function.
Change:
documentFilter("triggerDiv", "hideableDiv");
to:
documentFilter("#triggerDiv", "#hideableDiv"); // notice the '#'s to grab ids
It would be more concise to just toggle the hideableDiv whenever the checkbox state changes.
If the checkbox state is always unchecked on load, just hide the div on page load.
If the checkbox state is determined dynamically, then you'd need to check the prop checked state on page load to hide or show the div initially.
function documentFilter(trigger, target) {
$(trigger).on('change', function () {
$(target).toggle();
});
}
documentFilter("#triggerDiv", "#hideableDiv");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="checkbox" id="triggerDiv" > Some caption </label>
<div id="hideableDiv" class="well" style="display:none">
Some hidable content </div>
Your selectors aren't the best. I'd do the following:
Hide the div when the page loads using jQuery's .hide()
Listen for the checkbox to be clicked
When the checkbox is clicked, check to see if the current state of the checkbox is checked using this.checked
Based on the current state, either hide() or show()
DEMO: http://jsbin.com/zukobufefe/edit?html,js,output
$("#hideableDiv").hide();
$("input[type=checkbox]").click(function() {
if (this.checked)
{
$("#hideableDiv").show();
}
else
{
$("#hideableDiv").hide();
}
});
Your selectors are bad. If you want to find by id you shoud use # before id
To get checked state use .prop
You can use .toggle(state) to show/hide element according to passed state
Try this:
function documentFilter(trigger, target) {
var $target = $(target);
$(trigger).change(function() {
$target.toggle(this.checked);
});
}
documentFilter("#triggerDiv", "#hideableDiv");

Attach a checkbox javascript to a class

I have done 7 check boxes and code them to only one should be checked, and here is the code:
$j(document).ready(function(){
$j(':checkbox').bind('change', function() {
var thisClass = $j(this).attr('class');
if ($j(this).attr('checked')) {
$j(':checkbox.' + thisClass + ":not(#" + this.id + ")").removeAttr('checked');
}
else {
$j(this).attr('checked', false);
$j('.first-image').show();
$j('.hide-onload').hide();
}
});
});
and I had to create another 2 check boxes in the same page to choose between "yes" or "no" and they have another class
everything is fine except when I check the "Yes" "No" boxes it should not uncheck the first checked box because it is in different class.
The question is: How to make the code I have attach to work only with the class of the first 7 check boxes and make another one for the "Yes" "No" check boxes.
I hope I was clear enough, and here is the page link I am working on it that explains the problem http://www.cabas-durables.fr/magento/index.php/custom-contact/
Thank you in advance ....
You can separate your responsabilities with two additional classes:
$j('.normal-checkboxes:checkbox').bind(...);
$j('.yes-no:checkbox').bind(...);
And then wrap your checkboxes like this:
<div class="normal-checkboxes">
<input type="checkbox">
<input type="checkbox">
</div>
<div class="yes-no">
<input type="checkbox">
<input type="checkbox">
</div>
EDIT:
$j(document).ready(function(){
// When clicking a .normal-checkboxes..
$j('.normal-checkboxes:checkbox').bind('click', function() {
// Remove the property checked for all normal-checkboxes
$('.normal-checkboxes:checkbox').prop('checked', false);
// Add the property checked to the clicked one
$(this).prop('checked', true);
});
});

Change CSS based on certain DIV content

Hoping someone could help me with a bit of jquery or javascript. I have some DIV's that contain the values of a checkbox being either "1" or "0" depending on whether I check the box or not:
<div class="checkbox">1</div> //This is when the checkbox is checked
<div class="checkbox">0</div> //This is when the checkbox is NOT checked
The class for this DIV stays the same whether it is a 0 or a 1 so I need to have a conditional statement that says,
"If the contents of the DIV is 1 then show it"
AND
"If the contents of the DIV is 0, then hide it"
Would this be simple to do?
A filter would come in handy for such case..
$('.checkbox').filter(function () {
return $(this).text() == 0;
}).hide();
I would do it differently.
$("input#checkbox").change(function(){
$("div.checkbox").toggle(this.checked);
});
Considering that your checkbox is the one that it is altering the content of the <div> anyways.
Any time a checkbox is changed, look at your divs with class checkbox and if they have 1, show, else hide.
$('input[type="checkbox"]').on('change', function() {
$('.checkbox').each(function(){
if($(this).text() === '1'){
$(this).show();
}else{
$(this).hide();
}
});
});
If i have to do it then i would love to do in this way: http://jsfiddle.net/P2WmG/
var chktxt = $.trim($('.checkbox').text());
if (chktxt == 0) {
$('#checkbox').hide();
} else {
$('#checkbox').show();
}
You can use the :contains() Selector to select the divs based on their contents.
$('div.checkbox:contains("1")').show();
$('div.checkbox:contains("0")').hide();

Using custom jQuery radio buttons with CakePHP Form Helper

I'm using a custom jQuery plugin to convert radio buttons to actual images, and it works with basic checkboxes, but when using Cake's built-in input form helper, it acts more as a checkbox by not unchecking the already clicked options. Not only that, but it isn't populating $this->data (or sending anything when the form is submitted).
The js looks like this:
//##############################
// jQuery Custom Radio-buttons and Checkbox; basically it's styling/theming for Checkbox and Radiobutton elements in forms
// By Dharmavirsinh Jhala - dharmavir#gmail.com
// Date of Release: 13th March 10
// Version: 0.8
/*
USAGE:
$(document).ready(function(){
$(":radio").behaveLikeCheckbox();
}
*/
$(document).ready(function() {
$("#bananas").dgStyle();
var elmHeight = "15"; // should be specified based on image size
// Extend JQuery Functionality For Custom Radio Button Functionality
jQuery.fn.extend({
dgStyle: function()
{
// Initialize with initial load time control state
$.each($(this), function(){
var elm = $(this).children().get(0);
elmType = $(elm).attr("type");
$(this).data('type',elmType);
$(this).data('checked',$(elm).attr("checked"));
$(this).dgClear();
});
$(this).mouseup(function() {
$(this).dgHandle();
});
},
dgClear: function()
{
if($(this).data("checked") == true)
{
$(this).addClass("checked");
}
else
{
$(this).removeClass("checked");
}
},
dgHandle: function()
{
var elm = $(this).children().get(0);
if($(this).data("checked") == true)
$(elm).dgUncheck(this);
else
$(elm).dgCheck(this);
if($(this).data('type') == 'radio')
{
$.each($("input[name='"+$(elm).attr("name")+"']"),function()
{
if(elm!=this)
$(this).dgUncheck(-1);
});
}
},
dgCheck: function(div)
{
$(this).attr("checked",true);
$(div).data('checked',true).addClass('checked');
},
dgUncheck: function(div)
{
$(this).attr("checked",false);
if(div != -1)
$(div).data('checked',false).css({
backgroundPosition:"center 0"
});
else
$(this).parent().data("checked",false).removeClass("checked");
}
});
The PHP/Html looks like this:
<span id="bananas-cat" class="cat">
<?= $this->Form->radio('bananas',array(),array('legend' => false, 'id' => 'bananas', 'name' => 'category')); ?>
<label for="bananas">Bananas</label>
</span>
While it upon first inspection may look correct, when clicked, nothing gets passed within $this->data and it acts like a checkbox and doesn't unselect the value when I add an additional radio checkbox.
Although the radio functionality does work without CakePHP's html form helper like so:
<span id="animals-cat" class="cat">
<input type="radio" name="category" id="animals" />
<label for="animals">Animals</label>
</span>
If anyone can help me out here, I would be forever indebted. I've been trying to solve this for way too long now that I'm considering just scrapping the whole idea to begin with.
What I would suggest is see and compare the HTML output of example and one being generated by CakPHP, try to make it similar to example so that you can get your custom-radio-buttons working.
But if you can not do that I would highly recommend to override those helpers by some parameters so that you can get the exact HTML as an output and Javascript should work flawlessly.
Let me know if that does not work for you.

jQuery toggle() text in separate element

I am having some trouble getting a toggle function to work and need someone to help explain it to me.
My HTML (simplified):
<div id="filter_names"></div>
<div class="item">Option 1</div>
<div class="item">Option 2</div>
<div class="item">Option 3</div>
<div class="item">Option 4</div>
My jQuery (simplified)
$(".item").click(function(){
var tagname = $(this).html();
$('#filter_names').append(' > '+tagname);
$(".loading").show();
});
As you can see I am appending clicked items' value to the div at the top. This works fine, but i need it to be removed when i click it again.
I am pretty sure it needs a toggle() function but so far my attempts have been pretty fruitless.
Some guidance would be greatly appreciated.
EDIT: You can see what i want to achieve in this JSfiddle. It's working exactly how i want it to by appending a value to the end (like a breadcrumb link), but is not being removed when i click it again.
You need to look at the #filter_names contents and check if the clicked tag's value is already included, then remove it if it is, or add it otherwise:
if (filternames.indexOf(tagname) === -1) {
$('#filter_names').append(' > '+tagname);
} else {
$('#filter_names').text(filternames.replace(' > '+tagname, ''));
}
Working fiddle: http://jsfiddle.net/passcod/Kz3vx/
Note that you might get weird results if one tag's value is contained in another's.
<script type="text/javascript">
$(function(){
$(".item").click(function(){
var $this=$(this);
var tagname = ' > ' +$this.html();
//if has item-check class remove tag from filter_names
if($this.hasClass("item-click")){
var h=$("#filter_names").text();
$("#filter_names").text(h.replace(tagname, '' ));
}
else{
$('#filter_names').append(tagname);
}
$(this).toggleClass("item-click").toggleClass("item");
});
});
</script>
try this one...
$(this).toggleClass("item-click item");
this will add these classes alternatively when you click on div. or if you just want to remove this class on second click then you should write this in your click handler.
if( $(this).hasClass("item-click")){
$(this).removeClass("item-click");
}
EDITED -----
to remove appended html you can try this...
if($(this).hasClass("item-click")){
$("#filter_names").text("");
}
else{
$('#filter_names').append(tagname);
}
it's working HERE
hope this helps you!!
I like passcod's solution - here's an alternative that wraps the elements in divs and puts them in alphabetical order.
JSFiddle here. The sort function is from http://www.wrichards.com/blog/2009/02/jquery-sorting-elements/.
$(".item").click(function(){
var tagname = $(this).html();
var target = $('#filter_names').find('div:contains("> ' + tagname + '")');
if (target.is('*')) {
target.remove();
}
else $('#filter_names').append('<div class="appended"> > '+ tagname +'<div>');
function sortAlpha(a,b) {
return a.innerHTML > b.innerHTML ? 1 : -1;
}
$('#filter_names div').sort(sortAlpha).appendTo('#filter_names');
});

Categories

Resources