John Davidson

php - Run javascript on page load wordpress

0 comments
Message:


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!



My Answer:
You are close, but there is a small mistake in your code. You are not actually calling the function `conditionally_hide_show_checkout_field` inside the `window.onload` event. You need to add parentheses `()` after the function name to call it.

Here is the corrected code:

php
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()
{
?>

};


Now, the `conditionally_hide_show_checkout_field` function will be called on page load, and the input field should be hidden initially.

Rate this post

5 of 5 based on 2951 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us