views:

144

answers:

3

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/

+1  A: 

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);

udated 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

Reigel
great, that tells me which boxes are checked but how would I show the content of `wpbook_option_set_1` on load for example sense it's checked?
BandonRandon
see added texts.
Reigel
great work! You're a wizard! :)
BandonRandon
A: 

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

phungdinhvu
A: 

to checkout if a checkbox is checked you can use the following code :

$(':checkbox').change(function() {
  if ( $(this).checked == true ){
     //your code here
   }

});
stunaz
it's `this.checked` and not `$(this).checked`. if you use `$(this)`, it would be `$(this).attr('checked')` ;)
Reigel