Webflow sync, pageviews & more.
NEW

How can I keep custom radio buttons selected once clicked in Webflow using custom code?

TL;DR
  • Use native radio inputs in Webflow, give related buttons the same name, and style using wrappers with a class like .custom-radio.
  • Hide the inputs using opacity: 0; position: absolute, then apply JavaScript to toggle a .selected class based on input state via the change event.

To keep custom radio buttons selected after being clicked in Webflow using custom code, you need to ensure your buttons are properly connected to the browser's form state and styled to reflect the selection.

1. Use Webflow's Native Radio Button Elements

  • Drag a Radio Button element from the Add panel into your page.
  • Group related radio buttons using the same Name value under the Element Settings Panel.
  • Customize the visual style using Webflow’s Designer to hide the native input and style a custom label or wrapper.

2. Connect the Selection to the Visual Style

  • If you're using a custom design (like hiding the default radio and using a div for visuals), add a class like .custom-radio to each.
  • Add a click interaction using Webflow’s Interactions panel or apply logic via JavaScript to change the visual state (like addClass('selected')) when selected.

3. Use JavaScript to Maintain and Reflect Selection

You need a script that ensures:

  • When a radio is clicked, the visual selection updates correctly.
  • Other custom buttons in the same group are deselected.

Here’s how to do it:

  • Add the following inside the Before tag custom code area in the Page Settings:
// Assumes each custom radio button is wrapped in an element with class "custom-radio"document.querySelectorAll('.custom-radio input[type="radio"]').forEach(function(radioInput) {  radioInput.addEventListener('change', function() {    // Get all radios in the same group    const name = this.name;    document.querySelectorAll(`.custom-radio input[name="${name}"]`).forEach(function(radio) {      if (radio.checked) {        radio.closest('.custom-radio').classList.add('selected');      } else {        radio.closest('.custom-radio').classList.remove('selected');      }    });  });});
  • In Webflow:
  • Hide the native radio input via CSS (e.g., display: none).
  • Wrap each radio input in a parent element with the class custom-radio, and design the selection style on .custom-radio.selected.

4. Ensure Radio Inputs Are Not Removed on Publish

  • Webflow sometimes cleans unused or hidden fields. Avoid setting the radio input to display: none; use opacity: 0; position: absolute instead so it remains in the DOM and interactive.

Summary

To keep custom radio buttons selected in Webflow, use native radio inputs, hide them visually, wrap them in styled containers, and use JavaScript to sync selection states to visual classes by listening to the change event.

Rate this answer

Other Webflow Questions