Support » Developing with WordPress » Add onChange to Select and change a value based on that and with reveal field

  • I need to change certain fields based on the selected item in the Select box selection in Woocommerce. Based on a selection it needs to change the post code and a selection from another Drop Down that has drop downs of Suburbs

    I tried:

    add_action( 'wp_head', function () { ?>
    <script>
    
            
        function onChangeFunc(){
        
    var complex_name = document.getElementById('billing_selections').value; 
    var suburb = document.getElementById('billing_suburb');
    
    if complex_name == 'raslouwgardens' {
        document.getElementById("billing_suburb").value = suburb.options[complex_name.selectedIndex].text;
    
        document.getElementById("billing_postal").value = 1009;
    }
    }
    
    </script>
    <?php } );

    With the element:

              $fields['billing_estae'] = array(
             'label' => __('Estate', 'woocommerce'), // Add custom field label
            'placeholder' => _x('Estate', 'placeholder', 'woocommerce'), // Add custom field placeholder
            'required' => false, // if field is required or not
            'clear' => false, // add clear or not
            'type'  => 'select',
            'options'   => array(
             '' => 'Please select',
                            'gardens'   => 'Gardens', 
                            'tintle'    => 'Tintle',
                            'other'     => 'Other',
    
                           
            ),    
            'class' => array('my-css'),
            'priority' => 9,// 
       );

    A selection from here needs to change the post code however if they enter Other I need a text-box they can fill in (not sure where to add this and to leave it hidden unless Other is selected)

    • This topic was modified 2 weeks, 4 days ago by bcworkz. Reason: code format fixed
Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz

    (@bcworkz)

    Go ahead and add the extra field in PHP. Include a distinct class such as “hidden”. Add a CSS rule that hides this field by default using that class selector.

    In the change event handler, if “other” was selected, the script can remove the “hidden” class from the extra field so that it then is displayed. Also, if the selection is not “other”, then add the “hidden” class to ensure the extra field remains hidden. This accounts for someone selecting “other”, then changing their mind and selecting something else.

    Thread Starter rawald

    (@rawald)

    Hey there, Thanks alot for reply. How do I add the onChange though? When I tried in the PHP element onchange => onchangefunc it crashed the form

    Moderator bcworkz

    (@bcworkz)

    Use jQuery, or addEventListener() for straight JavaScript.

Viewing 3 replies - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.