HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Hide or show if radio button is checked

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
showradiobuttoncheckedhide

Problem

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

Solution

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



Show gallery
Hide gallery

The Gallery

Context

StackExchange Code Review Q#74709, answer score: 5

Revisions (0)

No revisions yet.