Steve
Steve

Reputation: 1775

Function called when checkbox is checked

I have a Wordpress option which is a checkbox, with id="is_custom_colour".

When this check box is checked, I want a hidden option to show.

I have code which works when the checkbox is clicked, but this fails if the option "is_custom_colour" is already checked. You have to click it (uncheck it), to show the hidden options.

This is the original code which works fine but is not functionally ideal (custom_colour is the id of the hidden option):

<script type="text/javascript">
jQuery(document).ready(function($) {

    $('#is_custom_colour').click(function() {
        $('#section-custom_colour').fadeToggle(400);
    });

    if ($('#is_custom_colour:checked').val() !== undefined) {
        $('#section-custom_colour_hidden').show();
    }

});
</script>

If I change this to

<script type="text/javascript">
jQuery(document).ready(function($) {

    if ($('#is_custom_colour:checked').val() !== undefined) {
        $('#section-custom_colour').fadeToggle(400);
    });

    if ($('#is_custom_colour:checked').val() !== undefined) {
        $('#section-custom_colour_hidden').show();
    }

});
</script>

It doesn't work.

Upvotes: 0

Views: 311

Answers (1)

Swarne27
Swarne27

Reputation: 5747

Try using, .is(':checked') to check whether the checkbox is checked

jQuery(document).ready(function($){
   if($('#is_custom_colour').is(':checked')){
      $('#section-custom_colour_hidden').show();
    }
});


<form id="form1" name="form1" method="post" action="">
    <label>
      <input name="checkbox" type="checkbox" id="is_custom_colour" value="checkbox" checked="checked" />
      Checkbox</label>   
</form>
<div id="section-custom_colour_hidden" style="display:none">HIDDEN AREA</div>

Upvotes: 2

Related Questions