DEV Community

coldbow
coldbow

Posted on

Poll Percentages in JavaScropt

Its a simple poll app in Js. where user vote count and percentages will change accordingly. But the problem i am facing is the percentages are not updated, lets say total vote is 5 and yes vote is 3 among them so yes vote percentage should be updates as the no votes comes along but it not been updated automatically.

HTML

> <!DOCTYPE html>
> <html lang="en">
> <head>
>   <meta charset="UTF-8">
>   <meta http-equiv="X-UA-Compatible" content="IE=edge">
>   <meta name="viewport" content="width=device-width, initial-scale=1.0">
>   <title>Document</title>
> </head>
> <body>
>   <fieldset>
>     <legend>do you like pizza</legend>
>     <div id="count"> 0</div>
>     <button id="btn">yes</button>
>     <br></br>
>     <div id="ncount"> 0</div>
>     <button id="Nbtn">no</button>
>     <br></br>
>     <div id="per"></div>
>   </fieldset>
>   <script src="main.js"></script>
> </body>
> </html>

Enter fullscreen mode Exit fullscreen mode

JS

let count = document.getElementById('count')
let ncount = document.getElementById('ncount')

let num = 0;
let nnum = 0;

document.getElementById('btn').addEventListener('click', () => {
  let nper = document.getElementById('per')
  num++

  let total = num + nnum

  let totalPercentages = num / total * 100

  count.innerHTML = num + " " + "percentages" + totalPercentages + '%'


  nper.innerHTML = nnum + num + '<div></div>' + "total vote cast"
})

document.getElementById('Nbtn').addEventListener('click', () => {
  let per = document.getElementById('per')
  nnum++
  let total = num + nnum
  let totalPercentages = nnum / total * 100
  ncount.innerHTML = nnum + " " + totalPercentages + '%'
  per.innerHTML = num + nnum + '<div></div>' + "total vote cast"
})
Enter fullscreen mode Exit fullscreen mode

Top comments (0)