samedi 19 septembre 2015

Show field only if checkbox is checked

I have the following code :

<div class="dk-form-group">
        <label class="dk dk-control-label" for=""><?php _e( 'Manage Items?', 'dk' ); ?></label>
        <div class="dk dk-text-left">
            <?php dk_post_input_box( $post->ID, '_manage_items', array('label' => __( 'Enable item management', 'dk' ) ), 'checkbox' ); ?>
        </div>
    </div>

    <div class="dk-form-group">
        <label class="dk dk-control-label" for="_item_qty"><?php _e( 'Item Qty', 'dk' ); ?></label>
        <div class="dk dk-text-left">
            <input type="number" name="_item" id="_item" step="any" placeholder="10" value="<?php echo !empty( $_stock ) ? wc_stock_amount( $_stock ) : 1; ?>">
        </div>
    </div>

Basically as you can guess, I am trying to show the input field only if the checkbox is checked.

I've been trying to add the following code :

$('_manage_items').click(function() {
  $('_item')[this.checked ? "show" : "hide"]();
});

So my final code looks like this :

<div class="dk-form-group">
            <label class="dk dk-control-label" for=""><?php _e( 'Manage Items?', 'dk' ); ?></label>
            <div class="dk dk-text-left">
                <?php dk_post_input_box( $post->ID, '_manage_items', array('label' => __( 'Enable item management', 'dk' ) ), 'checkbox' ); ?>

               <?php
            $('_manage_items').click(function() {
            $('_item')[this.checked ? "show" : "hide"]();
            }); ?>

            </div>
        </div>

        <div class="dk-form-group">
            <label class="dk dk-control-label" for="_item_qty"><?php _e( 'Item Qty', 'dk' ); ?></label>
            <div class="dk dk-text-left">
                <input type="number" name="_item" id="_item" step="any" placeholder="10" value="<?php echo !empty( $_stock ) ? wc_stock_amount( $_stock ) : 1; ?>">
            </div>
        </div>

But that just throwing errors. So I'm not sure if I am adding this snippet correctly to the correct place within the checkbox code and then I'm not sure if the names in the snippet $('_manage_items') and $('_item') are input correctly at all.

Any help would be much appreciated.




Aucun commentaire:

Enregistrer un commentaire