[SOLVED] 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.

<!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>
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"
})

vote percentage should be updates as the no votes comes along but it not been updated automatically.

There is no code that updates the yes percentage when you update the no percentage. So you will need to start there.

You can post this on stackoverflow.

can u show? having a bit of trouble to build that logic

You are already using the type of code you need, updating element values with .innerHTML:

ncount.innerHTML = ...

So you will need to update the other percentage value.

do i need to subtract it? i mean how should i go?

you can add some logging with console.log to see what code executes and when, you can also look in browser console tab to see if there are any errors

that i know, was talking about what logic i need to add when i press no button to update yes percentages accordingly.

Yes something like that, you need to work out how to calculate the other percentage. You have already done one side, you should be close to doing the rest of the logic.

i figure it out.

thank you

1 Like