Adjust dollar amount from outside the form
Say we want to have a button, outside the form, which adjusts the amount.
Let's make one (actually let's make two!). We'll put it below the form, and when a user clicks it, the form will scroll into view.
There are two tricks to this:
- we have the embedding page "type" into the form.
- we grab the amount to type in from the button text itself (any digits after the dollar sign).
Copy the code below into the page footer, and change the CONFIGURE THIS
part:
- specify the HTML
id
for the "dollar handle" button(s)
<script>
/* CONFIGURE THIS */
var dollarHandles = [
{ buttonID: 'btn-id-1' },
{ buttonID: 'btn-id-2' },
];
/* END CONFIGURATION */
/* Scroll to the donate form, and input the amount */
function scrollAndDonate(amount) {
var formID = 'gpap-donate-widget';
document.getElementById(formID).scrollIntoView({
behavior: 'smooth'
});
// the CSS selector which locates our input field:
var cssInputSelector = 'input[data-cy="amount"]';
var donateInputField = document.querySelectorAll(cssInputSelector)[0];
if (donateInputField) {
donateInputField.value = amount;
} else {
console.error('Failed to locate donate form input field');
}
}
/* Pull the desired amount from the button element.
* The amount can be in the format "$nn" or "$nn.nn"
* and this returns the amount (minus the dollar sign).
*/
function getDollarHandleAmount(buttonElement) {
var defaultAmount = '';
if (!buttonElement) {
return defaultAmount;
}
var dollarHandleText = buttonElement.innerText;
if (!dollarHandleText || typeof dollarHandleText !== 'string') {
return defaultAmount;
}
var dollarAmount = dollarHandleText.match(/\$(\d+\.?\d*)/)[1];
if (!dollarAmount) {
return defaultAmount;
}
return dollarAmount;
}
dollarHandles.forEach(function(handle) {
var dollarHandle = document.getElementById(handle.buttonID);
if (dollarHandle) {
dollarHandle.onclick = function(event) {
event.preventDefault();
scrollAndDonate(getDollarHandleAmount(event.target));
};
} else {
console.error('Page misconfigured: invalid dollar handle ID: ' + handle.buttonID);
}
});
</script>