Home › Forums › Backend Issues (wp-admin) › Run some JavaScript when field is selected › Reply To: Run some JavaScript when field is selected
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
}
}
`
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
The most recent ACF Chat Friday featured a live demo of how to register CPTs directly in the plugin, one of our most requested features. Check out the summary below for a replay of the demo, and don’t forget to register for the next session! https://t.co/k2KQ3WWBAz
— Advanced Custom Fields (@wp_acf) March 9, 2023
© 2023 Advanced Custom Fields.
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.