Home > OS >  something happens when I add .value in different locations
something happens when I add .value in different locations

Time:12-04

so I tried to add .value in two differnet locations and I just would like to know why

HTML code :

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <link rel="stylesheet" href="style.css" />
    <title>Guess My Number!</title>
  </head>
  <body>
    <header>
      <h1>Guess My Number!</h1>
      <p class="between">(Between 1 and 20)</p>
      <button class="btn again">Again!</button>
      <div class="number">?</div>
    </header>
    <main>
        <input type="number" class="guess" name="number" />
        <button class="btn check">Check!</button>
    <script src="script.js"></script>
  </body>
</html>

javascript code 1 :

var input = document.querySelector(".guess").value
const check = document.querySelector(".check")
const message = document.querySelector(".message")
var score = document.querySelector('.score')
var highScore = document.querySelector('.highscore')

check.addEventListener("click", function(){
    console.log(input)
})

result : will not log the input's value

javascript code 2 :

var input = document.querySelector(".guess")
const check = document.querySelector(".check")
const message = document.querySelector(".message")
var score = document.querySelector('.score')
var highScore = document.querySelector('.highscore')

check.addEventListener("click", function(){
    console.log(input.value)
})

result: will log the input's value

CodePudding user response:

In the first case it gets the value when the page loads, in the second when you click the button it gets the value again, updated from the input

  • Related