Home > Software design >  I want to be able to change a variable to true with the click of a button
I want to be able to change a variable to true with the click of a button

Time:02-04

So i want to make my button so it changes to true in the Script part. This is so a random number will appear in the p element


<!doctype html>
<html>
<button>
random number
</button>
<p id="randomnumber">

</p>



</html>
<script>
if (document.getElementById('button').clicked == true)
{
document.getElementById("randomnumber").innerHTML = (Math.floor(Math.random()*21) 2);

}


</script>

CodePudding user response:

Hi Jeremy try this code please.

<!doctype html>
<html>
<button id="button">
random number
</button>
<p id="randomnumber">

</p>



</html>
<script>
  document.getElementById('button').addEventListener('click', function() {
    document.getElementById("randomnumber").innerHTML = (Math.floor(Math.random() * 21)   2);
  })
</script>

CodePudding user response:

You're probably looking for element.addEventListener()

document.querySelector('#button').addEventListener('click', () =>
  document.querySelector("#random-number").textContent = Math.floor(Math.random() * 21)   2);
<button id="button">random number</button>
<p id="random-number"></p>

Some tips:

  • use dashes in element ID's
  • format your code cleanly
  • use document.querySelector() instead of document.getEementById()
  • use element.textContent instead of element.innerHTML
  •  Tags:  
  • Related