How to call a JavaScript method based on the Advanced Custom Field's value in WordPress?

128
March 08, 2022, at 5:20 PM

I have a custom field in the form of a checkbox in my WordPress website's admin panel. I want to load different JavaScript methods based on the selection of this checkbox. I have already tried the following approach:

<script>
    function setFirstStyle() {
        $('#faq-div').addClass('style-one');
    }
    function setSecondStyle() {
        $('#faq-div').addClass('style-two');
    }
    <?php if(!empty(get_field('my_custom_field')) && get_field('my_custom_field') == "Yes"):?>
            setFirstStyle();
    <?php else: ?>
            setSecondStyle();
    <?php endif; ?>
</script>

I also have put the relevant CSS styles for each style in my .cssfile, but the script is not working properly and I always get the default style (which is style-two) although I change the custom fields value in wp-admin page.

When I add a checkbox to my html code like below and I write a function to listen to that checkbox the issue is solved but I don't want to do this. I want to solve the issue with custom fields and without using any other html element.

<input type="checkbox" id="change-style"/>
<script>
    $('#change-style').on('change', function () {
        if (this.checked) {
            setSecondStyle();
        }
        else {
            setFirstStyle();
        }
    });
</script>

How can I fix this issue in WordPress?

Rent Charter Buses Company
READ ALSO
Retrieve the value of a variable that stores in local storage the options chosen by users in a dropdown list

Retrieve the value of a variable that stores in local storage the options chosen by users in a dropdown list

I need to retrieve the value of a variable that stores in local storage the options chosen by users in a dropdown list in order to use it elsewhere

147
Javascript function doesn&#39;t work when chrome auto-fill forms

Javascript function doesn't work when chrome auto-fill forms

I have a login form where, if the fields are filled with data, a javascript (jquery) adds a class to them

136
How to reset auto prefill URL after the page load?

How to reset auto prefill URL after the page load?

I would like to reset auto prefill URL after the page load because some of my menu will not work if there's is a URL on itIs this possible JQuery?

131