Question

How can I use JavaScript for polls with radio buttons?

Answer and Explanation

You can use JavaScript to create interactive polls with radio buttons by capturing user selections and processing them. Here's a breakdown of how to achieve this:

1. HTML Structure:

- First, set up your HTML form with radio buttons. Each radio button should have the same `name` attribute to group them, and a unique `value` attribute to identify the selected option. Include a submit button to trigger the JavaScript processing.

- Example HTML:

<form id="pollForm">
  <p class="qa-text">What is your favorite programming language?</p>
  <input type="radio" name="language" value="javascript" id="javascript"><label for="javascript">JavaScript</label><br>
  <input type="radio" name="language" value="python" id="python"><label for="python">Python</label><br>
  <input type="radio" name="language" value="java" id="java"><label for="java">Java</label><br>
  <button type="submit">Submit Vote</button>
</form>
<div id="result"></div>

2. JavaScript Logic:

- Use JavaScript to listen for the form's submit event. Prevent the default form submission behavior. Then, retrieve the selected radio button's value and display the result.

- Example JavaScript:

document.getElementById('pollForm').addEventListener('submit', function(event) {
  event.preventDefault();
  const selectedOption = document.querySelector('input[name="language"]:checked');
  if (selectedOption) {
    const resultDiv = document.getElementById('result');
    resultDiv.textContent = 'You voted for: ' + selectedOption.value;
  } else {
    alert('Please select an option.');
  }
});

3. Explanation:

- The JavaScript code first selects the form using its ID. It then adds an event listener for the 'submit' event. Inside the event handler, `event.preventDefault()` stops the form from submitting in the traditional way.

- `document.querySelector('input[name="language"]:checked')` selects the checked radio button within the group named 'language'.

- If a radio button is selected, the code retrieves its value and displays it in the `result` div. If no option is selected, it alerts the user.

4. Enhancements:

- You can extend this basic example to store votes in a database, display vote counts, or use AJAX to submit the vote without reloading the page.

By combining HTML radio buttons with JavaScript, you can create interactive and dynamic polls on your website. This approach allows for real-time feedback and user engagement.

More questions