Support

Account

Home Forums Backend Issues (wp-admin) Run some JavaScript when field is selected

Solving

Run some JavaScript when field is selected

  • Hi there, I want to run some JavaScript when the Product field is selected.

    How can I get the value of the select field (the product ID)? Once I get that, I can append it to the URL myself. Appreciate some pointers, thanks!

  • Thank you John! I managed to figure this out myself after some trial and error. My solution for anyone else who may be trying to get started with this:

    Step 1: create a message field for the product buy link and add an empty element to hold the text. In my case I used <code id="course--checkout_link"></code>

    Step 2: Add the following code to your functions.php file

    `
    add_action(‘acf/input/admin_footer’, ‘my_acf_input_admin_footer’);
    function my_acf_input_admin_footer() {
    // Only output this for my_courses
    if ( ‘my_courses’ == get_post_type() ) {
    ?>
    <script type=”text/javascript”>
    (function($) {

    // Get the site URL
    var origin = window.location.origin; // Returns base URL (https://example.com)

    // Print the URL on page load
    acf.add_action(‘ready’, function( $el ){
    // Get select value
    var currentOption = $(‘select#acf-field_5e69a22520434-field_5e69a28620436’).children(“option:selected”).val();
    $(‘#course–checkout_link’).text( origin + ‘/checkout/?add-to-cart=’ + currentOption );
    });

    // Update the URL when a new option is selected
    $(‘select#acf-field_5e69a22520434-field_5e69a28620436’).change(function(){
    var selectedOption = $(this).children(“option:selected”).val();
    $(‘#course–checkout_link’).text( origin + ‘/checkout/?add-to-cart=’ + selectedOption );
    });

    })(jQuery);
    </script>
    <?php
    }

    }
    `

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.