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?