I've created a checkbox and an input field and added these to my WooCommerce checkout. The input field should be hidden when the checkbox is unchecked, while showing up once the checkbox is checked.
This is working fine when the checkbox is clicked - but on initial page load the checkbox is unchecked but the input field is showing.
How am I able to run the javascript on initial page load, such that the input field is hidden.
This is the code I have right now:
function conditionally_hide_show_checkout_field() {
wc_enqueue_js( "
$('#gift_wrap').change(function() {
if ($(this).is(':checked') ) {
$('#personal_message_field').show();
} else {
$('#personal_message_field').hide();
}
});
" );
}
add_action( 'wp_footer', 'on_load_script' );
function on_load_script()
{
?>
<script type="text/javascript">
window.onload = function() { conditionally_hide_show_checkout_field };
</script>
<?php
};
I'm learning javascript, so it's probably something silly. But everyone has got to learn along the way, so I decided I'll just post my question and learn.
Thanks!
conditionally_hide_show_checkout_fieldshould beconditionally_hide_show_checkout_field()- to call a function you have to use the brackets.on_load_scriptshould be removed completely, the action you add should beconditionally_hide_show_checkout_field. And inside the JS code that is adding to the document, you should add a document ready handler, and inside trigger the change event on that element.add_action( 'woocommerce_after_checkout_form', 'conditionally_hide_show_checkout_field', 9999 ); function conditionally_hide_show_checkout_field() { wc_enqueue_js(" $('#gift_wrap').change(function() { if ($(this).is(':checked') ) { $('#personal_message_field').show(); } else { $('#personal_message_field').hide(); } }); Window.onload = function() { conditionally_hide_show_checkout_field()}; " ); };