I have added custom select box field using this code snippet in the givewp donation form.
add_action('givewp_donation_form_schema', function ($form) {
// Ensure the GiveWP FieldsAPI is loaded
if (!class_exists('Give\Framework\FieldsAPI\Select')) {
error_log('GiveWP Select class not found!');
return;
}
// Ensure the form object is of the correct type
if (!($form instanceof \Give\Framework\FieldsAPI\DonationForm)) {
error_log('Invalid form object provided!');
return;
}
$stateField = \Give\Framework\FieldsAPI\Select::make('state')
->label(__('State', 'give'))
->placeholder(__('Select a state', 'give'))
->defaultValue('');
// Insert the fields after the email field
try {
$form->insertAfter('email', $stateField);
} catch (Exception $e) {
error_log('Error inserting fields: ' . $e->getMessage());
}
});
now I tried to target this select box using custom script:
function enqueue_custom_givewp_script_code() {
global $post;
// Check if it's a single GiveWP form page or if the 'give_form' shortcode is present
if ( is_singular('give_forms') || ( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'give_form') ) ) {
// Enqueue the GiveWP script (required for dependencies)
wp_enqueue_script('give');
// Fetch states from the database
$states = get_states_from_database();
// Pass states data to JavaScript
wp_localize_script(
'give',
'givewp_custom_vars',
array(
'states' => $states, // Pass the states array
)
);
// Add your custom inline script
$custom_script = "
jQuery(document).on('give_form_loaded', function() {
console.log('GiveWP form loaded!');
// Fetch states data passed from PHP
var states = givewp_custom_vars.states;
// Target the state select box
var stateSelect = $('select[name=\"state\"]');
console.log(stateSelect);
if (stateSelect.length) {
console.log('State select box found!');
// Clear existing options
stateSelect.empty();
// Add a default 'Select a state' option
stateSelect.append($('<option>', {
value: '',
text: 'Select a state'
}));
// Loop through the states and add options
$.each(states, function(index, state) {
stateSelect.append($('<option>', {
value: state.id, // Use the appropriate column for the value
text: state.name // Use the appropriate column for the label
}));
});
console.log('States populated successfully!');
} else {
console.log('State select box not found!');
}
});
";
// Add the inline script after the GiveWP script
wp_add_inline_script('give', $custom_script);
}
}
add_action('wp_enqueue_scripts', 'enqueue_custom_givewp_script_code');
the script is being enqueued successfully, but give_form_loaded is not being triggered, so I am unable to target the select box. Can anyone tell what I am missing?