如何实现自定义单选框与WPForms内置单选框的选中同步及表单数据传递
Solution to Sync Custom Radio Selections & Calculated Fees to WPForms
Hey there, based on your existing setup, here's a practical JavaScript implementation that will sync your custom radio button choices to the WPForms fields, update the .wpforms-selected class on the WPForms list items, and pass the calculated fee value through:
First, add this script to your theme's functions.php (enqueued properly) or directly into a custom HTML block/script tag on the page containing the form:
document.addEventListener('DOMContentLoaded', function() { // Get references to core elements const customRadios = document.querySelectorAll('.btn-group input[name="wpforms[fields][19]"]'); const wpformsRadioList = document.getElementById('wpforms-320-field_19'); const wpformsRadios = wpformsRadioList.querySelectorAll('input[name="wpforms[fields][19]"]'); // Core sync logic function syncSelections(selectedCustomRadio) { // Grab label text to match WPForms radio values const selectedLabel = selectedCustomRadio.nextElementSibling.textContent.trim(); // Get the calculated fee from the custom radio's value const feeValue = selectedCustomRadio.value; // Update WPForms radio state and list item classes wpformsRadios.forEach(radio => { const listItem = radio.closest('li'); if (radio.value === selectedLabel) { radio.checked = true; listItem.classList.add('wpforms-selected'); } else { radio.checked = false; listItem.classList.remove('wpforms-selected'); } }); // Sync fee to your WPForms fee field (replace field_20 with your actual field ID) const feeField = document.querySelector('input[name="wpforms[fields][20]"]'); if (feeField) { feeField.value = feeValue; // Trigger change event to ensure WPForms picks up the update feeField.dispatchEvent(new Event('change')); } } // Initialize sync for default checked radio on page load const defaultCheckedCustom = document.querySelector('.btn-group input[name="wpforms[fields][19]"]:checked'); if (defaultCheckedCustom) { syncSelections(defaultCheckedCustom); } // Listen for changes on custom radios customRadios.forEach(radio => { radio.addEventListener('change', function() { syncSelections(this); }); }); });
Key Details for Your Setup:
- DOMContentLoaded: Ensures the script runs only after all page elements are fully loaded, avoiding missing element errors.
- Class Toggling: The script targets the parent
<li>of each WPForms radio button to add/remove the.wpforms-selectedclass, matching WPForms' native activation behavior. - Fee Sync: Replace
field_20in the script with the actual ID of your WPForms fee field (you can find this by inspecting the fee input'snameattribute, e.g.,wpforms[fields][20]). This works for visible or hidden fields. - Initial Sync: Handles the default checked radio button on page load so the WPForms state matches your custom form from the start.
内容的提问来源于stack exchange,提问作者Александр Макаров
相关产品推荐
相关产品推荐

