Grace
Grace

Reputation: 45

JavaScript How to Get Keyboard to Push() new Input via Buttons

The title is kinda confusing because I find it hard to explain. Basically, I can get 1 input button to have one id name that a JavaScript function will store into a variable and display it by replacing an empty paragraph tag with the variable. However, I can't get it to work with multiple buttons with the same function, since I'm trying to get a number keypad going with buttons, and having it display the result. I think I need to use the push() method to somehow add values, then click a submit button, then have the resulting string displayed. I know how to use push with known variables, but I don't know how to implement it with unknown variables, though:

    var fruits = ["Banana", "Orange", "Apple", "Mango"];
    fruits.push("Kiwi");

Anyways, my code is here, with the input buttons with only 1 button with the i, and etc. jQuery answers are welcome, but I don't prefer jQuery, as I'm asking about JavaScript.

<!DOCTYPE html>
<html>
<head>
    <title>Desperate</title>

<script type="text/javascript">

        function othername() {
    var inputinput = document.getElementById("userInput").value;
    var n = inputinput.length;
    document.getElementById("demo").innerHTML = n;
   }

</script>
</head>
<body>
<p id="demo"></p>
<input id="text" type="text">
</div>

      <div>
          <input id="userInput" type="button" value="1" onclick="othername();" />
          <input id="btn2" type="button" value="2" onclick="othername();" />
          <input id="btn3" type="button" value="3" onclick="othername();" />
      </div>

</body>
</html>

All help is greatly appreciated! Thank you!

Upvotes: 0

Views: 351

Answers (1)

gforce301
gforce301

Reputation: 2984

You should bind your onclick event handler in a different way. Then you can examine the incoming event in your "othername" function and get the value of the element clicked.

<!DOCTYPE html>
<html>
<head>
    <title>Desperate</title>

    <script type="text/javascript">

        function othername(e) {
            var n = e.srcElement.value || '';
            document.getElementById("demo").innerHTML = n;
        }

    </script>
</head>
<body>
    <div>
        <p id="demo"></p>
        <input id="text" type="text">
    </div>

    <div id="btns">
        <input id="userInput" type="button" value="1" />
        <input id="btn2" type="button" value="2" />
        <input id="btn3" type="button" value="3" />
    </div>

    <script>
        var btnC = document.getElementById("btns");
        btnC.onclick = othername;
    </script>

</body>
</html>

Upvotes: 1

Related Questions