JSFiddle - React, Tailwind, and code Playground
by Prathameshsb
HTML
<div class="poll-widget">
<h2 class="poll-question">Who will win the Soccer Champions League this year?</h2>
<div class="poll-option">
<input type="radio" name="vote" value="Real Madrid"> Real Madrid
</div>
<div class="poll-option">
<input type="radio" name="vote" value="Liverpool"> Liverpool
</div>
<div class="poll-option">
<input type="radio" name="vote" value="Bayern Munich"> Bayern Munich
</div>
<div class="poll-option">
<input type="radio" name="vote" value="Manchester City"> Manchester City
</div>
<div class="poll-submit">
Submit
</div>
</div>
CSS
.poll-widget {
width: 500px;
margin: 0 auto;
}
.poll-question {
font-size: 24px;
margin-bottom: 10px;
}
.poll-option {
margin-bottom: 5px;
}
.poll-option input {
width: 20px;
height: 20px;
margin-right: 5px;
}
.poll-submit {
width: 100px;
margin-top: 10px;
background-color: blue;
color: white;
font-size: 16px;
padding: 10px;
}
JavaScript
// Get the poll widget element
const pollWidget = document.querySelector('.poll-widget');
// Get the submit button element
const submitButton = document.querySelector('.poll-submit');
// Add an event listener to the submit button
submitButton.addEventListener('click', function() {
// Get the selected vote option
const selectedVoteOption = pollWidget.querySelector('input[name="vote"]:checked');
// If there is a selected vote option, then submit the vote
if (selectedVoteOption) {
// Create a new HTTP request
const xhr = new XMLHttpRequest();
// Open a POST request to the server
xhr.open('POST', '/submit-vote');
// Set the request header
xhr.setRequestHeader('Content-Type', 'application/json');
// Send the request with the vote data
xhr.send(JSON.stringify({
vote: selectedVoteOption.value
}));
// When the request is complete, update the poll widget with the results
xhr.onload = function() {
// Parse the JSON response
const response = JSON.parse(xhr.responseText);
// Update the poll widget with the results
pollWidget.innerHTML = `
<h2>${response.question}</h2>
<div>${response.options.map(option => `<div class="poll-option">${option.label} (${option.count})</div>`).join('')}</div>
`;
};
}
});