Hide or show if radio button is checked I was recently working on a project, something jQuery-related for WP-Admin area.

I enable post-formats and create metaboxes for these post-formats, so at the end I tried to hide these metaboxes until the user checks the radio button. I just want to know if there is a better way I can write this code.

// hide the metabox at start
$('#gallery-box').hide();

// fetch the id name of checked post-format 
var idName = $('input.post-format:checked').attr('id');

// display the metabox if the fetched value matched
if ( idName === 'post-format-gallery' ) {
    $('#gallery-box').show();
}

// show or hide
$('.post-format').click(function(){
    idName = $(this).attr('id');
    if ( $(this).is(':checked') ) { 
        if ( idName === 'post-format-gallery' ) {
            $('#gallery-box').show();
        } else {
            $('#gallery-box').hide();
        }
    }
});
If you know exactly which radio button you are interested in, then you should prefer to select it by ID, for performance.  Presumably, your radio buttons will be part of a group with the same name, so it would be more conventional to select the elements by the name instead of by a class.

If you have to conditionally call .show() and .hide(), you can use .toggle().

Avoid hard-coding hide() as the initial state.  It would be better to have the "Hide" radio button marked as checked in the HTML, then let the JavaScript follow suit.  To bind an event handler and execute it right away, you could use .trigger(), but note that triggering the 'click' event also toggles the radio state, so you'll want to make a separate 'init-post-format' event type.



$(function() {
    $('input[name=post-format]').on('click init-post-format', function() {
        $('#gallery-box').toggle($('#post-format-gallery').prop('checked'));
    }).trigger('init-post-format');
});
&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"&gt;&lt;/script&gt;

&lt;label&gt;&lt;input type="radio" name="post-format" id="post-format-gallery"&gt;Show gallery&lt;/label&gt;
&lt;label&gt;&lt;input type="radio" name="post-format" checked&gt;Hide gallery&lt;/label&gt;

&lt;div id="gallery-box" style="border: 1px solid red;"&gt;The Gallery&lt;/div&gt;