show hide content depending if a checkbox is check

2019-05-07 03:58发布

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/

3条回答
贼婆χ
2楼-- · 2019-05-07 04:23

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

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

});
查看更多
Bombasti
3楼-- · 2019-05-07 04:30

Try this:

$("input[type=checkbox]:checked").each(fun....
查看更多
做个烂人
4楼-- · 2019-05-07 04:39

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

查看更多
登录 后发表回答