Home > Software engineering >  Why isnt my button displaying value onto the div
Why isnt my button displaying value onto the div

Time:08-20

I want the button with the id of number1 to display the value of 1 on to the input box which has the id of quest which is short for question.I also want to know if my code can be made more readable.

<!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>Calucator</title>
    <style>
        body{
            text-align: center;
        }
    </style>
    <script>
        const quest = document.getElementById("quest");
        const data = quest.value;
        const yourElement = document.createElement("div");
      
        function nums(){
        const num1 = document.getElementById('number1').innerText = 1;
        data.textContent = num1;
    }
    function run() {
        nums()
        yourElement.textContent = data
        quest.appendChild(yourElement);
    }
    
       </script>
</head>
<body>
    <h1>Calucator</h1>
    <input type="number" placeholder="Enter now" name="" id="quest">
    <button onclick="run()">=</button>
    <br>
    <button onclick="" id="number1">1</button>
</body>
</html>

CodePudding user response:

<script>
    const quest = document.getElementById("quest");
    const data = quest.value;
    const yourElement = document.createElement("div");
    //PROBLEM 1: You are not attaching yourElement to the DOM. See Element.insertBefore / Element.appendChild
    function nums(){
      const num1 = document.getElementById('number1').innerText = 1;
      data.textContent = num1;
    }
    function run() {
      nums()
      yourElement.textContent = data
      quest.appendChild(yourElement);
    }

   </script>

And

<button onclick="run()">=</button>

Problem 2: Don't use inline element event handling. It isn't safe and Content-Security-Policy won't allow it. Instead, use JavaScript Element.addEventListener(...)

  • Related