0

So I tried to make a button, that when pressed would change the input value.

    <input  id="inp" type="text" name="" value="">
    <button id="numb1" onclick="number()" type="button" name="button">1</button>
    <button id="numb2" onclick="number()" type="button" name="button">2</button>
    <button id="numb3" onclick="number()" type="button" name="button">3</button>

    <script type="text/javascript">

        function number(){
          var x = document.querySelectorAll("numb1, numb2, numb3").innerHTML;
          document.getElementById("inp").value = x;

          console.log(x);
        }

    </script>

But for some reason the value is undefined. Why is it undefined?

Marc
  • 2,920
  • 3
  • 14
  • 30
Marihuan
  • 41
  • 4
  • 1
    `document.querySelectorAll("numb1, numb2, numb3")` returns a NodeList, over which you must iterate in order to get `innerHTML`. See the linked duplicate post. Also `` elements contain nothing, so `innerHTML` will only ever be `null` or `''`. You need to use [`HTMLInputElement.value`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement) to retrieve the entered values. – David Thomas Oct 14 '20 at 11:41
  • `x` is undefined, x does not return anything – Marc Oct 14 '20 at 11:41

1 Answers1

1

    function number(x){
      document.getElementById("inp").value = x;
      console.log(x);
    }
<input  id="inp" type="text" name="" value="">
<button id="numb1" onclick="number(1)" type="button" name="button">1</button>
<button id="numb2" onclick="number(2)" type="button" name="button">2</button>
<button id="numb3" onclick="number(3)" type="button" name="button">3</button>

Try this

Dipankar Maikap
  • 447
  • 4
  • 13