【问题标题】:Get the label text from a custom checkbox with javascript in WooCommerce checkout在 WooCommerce 结帐中使用 javascript 从自定义复选框中获取标签文本
【发布时间】:2018-04-27 01:07:40
【问题描述】:

我在 woocommerce 结帐页面上为复选框添加了一些 javascript,它可以将文本框值复制到另一个复选框。

但它不起作用。

这是我使用的代码:

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
}

我做错了什么以及如何从复选框标签中获取文本?

【问题讨论】:

    标签: php jquery wordpress woocommerce checkout


    【解决方案1】:

    你最好试试这个,使用 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
    }
    

    代码进入您的活动子主题(或主题)的 function.php 文件或任何插件文件中。

    经过测试并且可以工作……

    【讨论】:

      猜你喜欢
      • 2020-09-02
      • 1970-01-01
      • 2018-01-03
      • 1970-01-01
      • 2021-04-03
      • 2018-08-14
      • 2017-01-20
      • 2021-07-10
      • 2019-01-16
      相关资源
      最近更新 更多