Actually your question is off-topic here, because it’s javascripts specific and not specific to WordPress. But I’m answering it and making it more WordPress-centric so that others get help too.
The following function will enqueue a custom.js
file from your theme folder’s /js
subfolder to only admin panel (put it in functions.php
of your theme):
function my_admin_scripts() {
wp_enqueue_script( 'custom-js', get_template_directory_uri() .'/js/custom.js', array('jquery'), '', true );
}
add_action( 'admin_enqueue_scripts', 'my_admin_scripts' );
Now in the custom.js
file write down the following code:
jQuery(document).ready(function($) {
var field_one = $('#field_one');
var field_two = $('#field_two');
//hiding the field first
field_one.hide();
field_two.hide();
//on value change
$('[name="ecpt_gender"]').on('change', function(){
//we're checking what the value we've got
if( $(this).val() === 'Female' ) {
field_one.show(); //you can use slideDown() instead of show() for some animation
field_two.show();
} else {
field_one.hide();
field_two.hide();
}
});
});
If you want to load the scripts only to a certain page, use $current_screen
Global inside the function:
function my_admin_scripts() {
global $current_screen;
//var_dump( $current_screen ); //check what you've got using this variable
if( 'post.php' === $current_screen || 'post-new.php' === $current_screen )
wp_enqueue_script( 'custom-js', get_template_directory_uri() .'/js/custom.js', array('jquery'), '', true );
}
add_action( 'admin_enqueue_scripts', 'my_admin_scripts' );
Always take precaution about JS-based show/hide fields, because they are good when inserting data, but they may not functional when updating/editing data. So take precaution there like the following:
Inside your metabox fields use get_post_meta()
and show the fields accordingly:
$ecpt_gender_db_val = get_post_meta( $post_id, 'field_name', true ); //fetching single value
if( $ecpt_gender_db_val && $ecpt_gender_db_val === 'Female' ) {
//show the fields associated with 'Female' value
}
But in my opinion it’s safer doing JS more specific, if that’s specific only to the New Post page:
var field_one = $('body.post-new-php #field_one');
Doing so will make the item selection more specific to only the add new page, and it won’t be applicable to the edit page. I’m using the dynamic <body>
class to target page-specific items.