Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Script to make the mailing address fields required in a donation page if the "mailing address" button is clicked. Removes the required mark and clears the fields when the "mailing address" is not clicked.
<script type="text/javascript">
(function() {
// Note to developers. jQuery doesn't like to return elements hidden by CSS.
// We're using the DOM in this solution to get around that restriction.
document.addEventListener('DOMContentLoaded', function () {
// Gather the mailing address fields.
var mailing = document.querySelector('#mailing');
//if (mailing == null) { return}
var addressFields = Array.from(mailing.querySelectorAll('#mailing input,#mailing select'))
.filter(function(e) { return e.type != 'hidden'; })
.filter(function(e) { return e.name != 'address_line_2'; })
var addressFieldNames = addressFields.map(function(e) { return e.name; })
var requiredField = document.querySelector('input[type=hidden][name=required]');
var requireds = requiredField
.value
.split(',')
.filter(function(v) { return v.trim().length != 0; })
var requiredHTML = '<span class="required">*</span>';
// Function to make the mailing address fields required.
// Note that the input/select is embedded in the label (sigh).
function requireMailingAddressFields() {
requiredField.value = [].concat(requireds, addressFieldNames).join(',');
addressFields.forEach(function(e) {
var label = e.parentNode.querySelector('label');
label.innerHTML = label.innerHTML + requiredHTML;
})
}
// Function to clear the mailing address fields and make them optional.
// This stops salsa from thinking they are required when they are not visible.
function optionMailingAddressFields() {
requiredField.value = requireds.join(',');
addressFields.forEach(function(e) {
e.value = '';
var label = e.parentNode.querySelector('label');
label.innerHTML = label.innerHTML.replace(requiredHTML, '');
});
document.querySelector('input[name=address_line_2]').value = '';
}
// Function to make the mailing address fields required if the "Add mailing address"
// radio button is clicked. The same fields are cleared and made optional if the
// "Add mailing address" rado button is not clicked.
// @param Object event click event object
function handleMailingAddress(event) {
if (document.querySelector('#mailingYes').checked) { requireMailingAddressFields(); }
if (!document.querySelector('#mailingYes').checked) { optionMailingAddressFields(); }
}
// Wire up the click Listeners.
document.querySelector('#mailingYes').addEventListener('click', handleMailingAddress);
document.querySelector('#mailingNo').addEventListener('click', handleMailingAddress);
});
})();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.