All Posts

Easily create pricing tables with toggled views on WordPress

Published: April 28, 2023
Share:
Image
// Hide the annual section by default
const annualSection = document.getElementById('annual');
annualSection.style.display = 'none';

// Listen for changes to the checkbox
const checkbox = document.getElementById('checkbox');
checkbox.addEventListener('change', function() {
  if (checkbox.checked) {
    // Show the annual section and hide the monthly section
    annualSection.style.display = 'block';
    const monthlySection = document.getElementById('monthly');
    monthlySection.style.display = 'none';
  } else {
    // Show the monthly section and hide the annual section
    const monthlySection = document.getElementById('monthly');
    monthlySection.style.display = 'block';
    annualSection.style.display = 'none';
  }
});

The code starts by selecting the HTML element with the ID “annual” and storing it in the variable annualSection. It then sets the CSS display property of annualSection to “none”, effectively hiding it by default.

Next, it selects the HTML element with the ID “checkbox” and stores it in the variable checkbox. It adds an event listener to the checkbox, listening for changes in its state.

When the checkbox is checked, the code executes the code block inside the if statement. It shows the annualSection by setting its display property to “block”, and hides the “monthly” section by setting its display property to “none”.

Conversely, when the checkbox is unchecked, the code executes the code block inside the else statement. It shows the “monthly” section and hides the annualSection.

In summary, this code provides a simple functionality where a checkbox controls the visibility of two sections on a webpage. When the checkbox is checked, the annual section is displayed while the monthly section is hidden, and vice versa when the checkbox is unchecked.