Open In App

Create a User Polls Project using HTML CSS & JavaScript

Last Updated : 28 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Creating a user polls project has various valuable purposes, including gathering feedback, engaging users, personalizing content, fostering community, conducting research, A/B testing, and improving the user experience. Clear objectives are crucial, and in this example, we focus on collecting data on users' preferences for programming. In this article, we will explore how to implement a user polls project using HTML, CSS, and JavaScript.

Prerequisites:

Preview Image:

Screenshot-2023-09-19-231226
Output Image

Approach

We have a clear set of observations to guide the thorough implementation of this project. Let's begin by creating the basic HTML structure based on the project description we have discussed above.

  • There are two radio buttons for user input.
  • At the top, there is a paragraph presenting the question.
  • There is a button with the value attribute set to 'vote.'
  • At the bottom, there are results displayed for 'Yes' and 'No,' along with their respective counts.
  • We can notice that the background color is distinct.
  • The position is centered, and text elements are aligned to the center.
  • In this project, when we click the 'Vote' button, the values of 'Yes' and 'No' should either increase or remain the same, depending on the user's choice.
  • To achieve this, we will utilize the getElementById method in JavaScript, which will allow us to increment the counters for 'Yes' and 'No' accordingly.
  • Subsequently, the updated counts will be reflected in the output.

Example: Below is the basic implementation of the above approach.

JavaScript
document.addEventListener("DOMContentLoaded", function () {
    const pollForm = 
        document.getElementById("poll-form");
    const yesCount = 
        document.getElementById("yes-count");
    const noCount = 
        document.getElementById("no-count");
    let yesVotes = 0;
    let noVotes = 0;

    pollForm.addEventListener("submit", function (e) {

        // It will help to prevent the submission of 
        // form, so that following code can execute
        e.preventDefault();
        const formData = new FormData(pollForm);
        const userVote = formData.get("vote");

        if (userVote === "yes") {
            yesVotes++;
        } else if (userVote === "no") {
            noVotes++;
        }
        updateResults();
    });

    function updateResults() {
        yesCount.textContent = yesVotes;
        noCount.textContent = noVotes;
    }
});
HTML CSS

Output:

userPollGif
Output

Next Article

Similar Reads