Adding a toggle button enhances the user experience by allowing users to show or hide specific elements dynamically. In SuiteCommerce Advanced (SCA), a toggle button can be used to reveal additional form fields or sections without cluttering the UI. This article provides a step-by-step guide on implementing a toggle button to show or hide a purchase order input field.
Why Use a Toggle Button?
A toggle button is useful when:
- You want to hide optional fields until they are needed.
- You want to create a cleaner and more organized layout.
- You want to improve usability without removing functionality.
Implementing the Toggle Button in SuiteCommerce Advanced
The following sample code extends the PurchaseNumberModule to add a toggle button that shows or hides the purchase order input field dynamically.
_.extend(PurchaseNumberModule.prototype, {
getContext: _.wrap(PurchaseNumberModule.prototype.getContext, function (fn) {
var context = fn.apply(this, _.toArray(arguments).slice(1));
$(document).ready(function () {
const titleElement = $(‘.order-wizard-paymentmethod-purchasenumber-module-title’);
const inputField = $(‘.order-wizard-paymentmethod-purchasenumber-module-purchase-order-value’);
// Check if the toggle button is already added
if (!$(‘#purchase-order-toggle-btn’).length) {
titleElement.wrap(‘<div class=”purchase-order-header”></div>’);
titleElement.parent().append(
‘<i id=”purchase-order-toggle-btn” class=”icon-chevron-down” aria-expanded=”false” style=”cursor: pointer;”></i>’
);
}
// Hide the purchase order input field by default
inputField.hide();
// Select the toggle button
const toggleButton = $(‘#purchase-order-toggle-btn’);
// Toggle button functionality
toggleButton.on(‘click’, function () {
const isExpanded = toggleButton.attr(‘aria-expanded’) === ‘true’;
toggleButton.attr(‘aria-expanded’, !isExpanded);
if (!isExpanded) {
inputField.show();
toggleButton.removeClass(‘icon-chevron-down’).addClass(‘icon-chevron-up’);
} else {
inputField.hide();
toggleButton.removeClass(‘icon-chevron-up’).addClass(‘icon-chevron-down’);
}
});
});
return context;
})
});
Using a toggle button improves the overall user experience by making forms dynamic and easier to navigate. This method ensures that optional fields remain accessible while keeping the page layout uncluttered.