Pranav Patel
Pranav Patel

Reputation: 121

Get the label text from a custom checkbox with javascript in WooCommerce checkout

I am adding some little piece of javascript on woocommerce checkout page for the checkbox which can copy the text box value to another.

But it is not working.

Here is the code that I use:

add_action('woocommerce_before_checkout_form', 'cw_custom_checkbox_fields');
function cw_custom_checkbox_fields( $checkout ) {

    woocommerce_form_field( 'custom_checkbox', array(
        'type'          => 'checkbox',

        'label'         => __('Check if both addresses are same'),
        'required'  => false,
    ), $checkout->get_value( 'custom_checkbox' ));

    ?>
        <script type="text/javascript">
            var allgenders = document.getElementsByName("custom_checkbox");  

        </script>
    <?php
}

What I am doing wrong and how can I get the text from the checkbox label?

Upvotes: 1

Views: 406

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254363

You should better try this, getting the text label value (and the checked property of the checkbox) using jQuery:

add_action('woocommerce_before_checkout_form', 'cw_custom_checkbox_fields');
function cw_custom_checkbox_fields( $checkout ) {

    woocommerce_form_field( 'custom_checkbox', array(
        'type'          => 'checkbox',
        'label'         => __('Check if both addresses are same'),
        'required'  => false,
    ), $checkout->get_value( 'custom_checkbox' ));

    ?>
        <script type="text/javascript">
            jQuery(function($){
                var allgenders = $('p#custom_checkbox_field > label').text(),
                    checkedValue;
                console.log('Label text: '+allgenders); // Output the label text in browser console (for test)

                // optionally get the checked value of the checkbox
                $('input[name^="custom_checkbox"]').click(function(){
                    checkedValue = $(this).prop('checked'); // Get the checked value
                    console.log('Is checked: '+checkedValue); // Output checked value in console browser in browser console (for test)
                })
            });
        </script>
    <?php
}

Code goes in function.php file of your active child theme (or theme) or also in any plugin file.

Tested and works…

Upvotes: 1

Related Questions