Skip to content

Commit

Permalink
update js to match
Browse files Browse the repository at this point in the history
  • Loading branch information
Barny-Thorpe committed Mar 20, 2024
1 parent 18bdddc commit 4dc97e8
Showing 1 changed file with 31 additions and 19 deletions.
50 changes: 31 additions & 19 deletions public/js/gf-giftaid-field-frontend.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,40 +6,52 @@
*/

document.addEventListener('DOMContentLoaded', () => {
determineDonationTotalMethod();
initGiftAid();
});

function determineDonationTotalMethod() {
/**
* Updates the gift aid display, based on a chosen field changing.
*/
function initGiftAid() {
const totalSelector = totalFieldSelector() || '.gfield.gfield--input-type-total';
window.gform.addAction('gform_input_change', (elem) => {
const total = getTotalAmount(elem, totalSelector);
if (! total || !total.donation || !total.giftAidTotal) {
return;
}
updateGiftAidDisplay(total);
}, 10);
}

/**
* Gets the selector of the total field, selected in the gift aid field settings.
* Will be in the format 'field_<form_id>_<field_id>' and will be an id so the selector will be prefixed by #.
* @returns {string} The class of the total field.
*/
function totalFieldSelector() {
const giftAidComponent = document.querySelector('.gift-box-wrapper');
if (! (giftAidComponent instanceof HTMLElement)) {
return;
return '';
}
const donationTotalInput = giftAidComponent.querySelector('input.donation-total-select');
if (!(donationTotalInput instanceof HTMLInputElement)) {
return;
}
const donationTotalSelection = donationTotalInput.value;
if ("ginput_total" === donationTotalSelection) {
window.gform.addAction('gform_input_change', updateGFFromTotal, 10);
return '';
}
}

function updateGFFromTotal(elem) {
const total = getTotalAmount(elem);
if (! total || !total.donation || !total.giftAidTotal) {
return;
const fieldId = donationTotalInput.value;
if (!fieldId) {
return '';
}

updateGiftAidDisplay(total);
return `#${fieldId}`;
}

/**
* Gets the total amount donated and updates the Gift Aid total.
* @param {HTMLElement} elem
* @param {HTMLElement} elem The element that has changed.
* @param {string} totalSelector selector of the chosen total field.
* @returns {Donation} The total amount donated.
*/
function getTotalAmount(elem) {
if (! (elem instanceof HTMLInputElement) || ! elem.classList.contains('ginput_total')) {
function getTotalAmount(elem, totalSelector) {
if (! (elem instanceof HTMLInputElement) || ! elem.closest(totalSelector)) {
return '';
}
const totalValueStr = elem.value;
Expand Down

0 comments on commit 4dc97e8

Please sign in to comment.