2017-11-14 15 views
1

テキストボックスの値を別のものにコピーできるチェックボックスのwoocommerceチェックアウトページにjavascriptを少し追加します。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 
} 

やっているとどのように私は、チェックボックスのラベルからテキストを得ることができますか?

答えて

0

方が良いのjQueryを使用してテキストラベル値(チェックボックスのcheckedプロパティ)を取得し、これを試してみてください:

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ファイルに行きますまたはテーマ)または任意のプラグインファイルでも使用できます。

テスト済みで、動作...

関連する問題