Home > Software design >  Trying to take input from HTML and do computation with it in Javascript
Trying to take input from HTML and do computation with it in Javascript

Time:04-03

I’m trying to get the computer to take an input from the HTML and add and multiply some number to it in Javascript. I’m from python and the variable system in Javascript makes no sense to me, so can someone please lmk what to do?

        <div class = "text">How much energy do you use?</div>
        <input id = "q1" type = "text" placeholder = "# of KilaWatts"></input>
        <button type="button" onclick="getInputValue();">Submit</button>
        <!-- Multiply InputValue by 3 and Add 2 —->

I tried to do something with parseInt, and parseString, but it didn’t work as it would just not run.

CodePudding user response:

It's not that hard. try to play with the below code. Cheers!!

<html>
<body>
    <label for="insertValue">Enter Your Value:</label>
    <input type="text" id="insertValue">

    <button onclick="Multiply()">Multiply</button> <!-- Calling to the JS function on button click -->
    <p id="answer"></p>

    <!-- Always link or write your js Scripts before closing the <body> tag -->
    <script>
        function Multiply() {
            let value = document.getElementById("insertValue").value; //get the inserted  Value from <input> text box
            let answer = 0;

            //Your Multiplication
            answer = value * 2 * 3;

            //Display answer in the <p> tag and it id ="answer"
            document.getElementById("answer").innerText = "Your Answer is: "  answer;

        }
    </script>
</body>
</html>

CodePudding user response:

Easy (to understand) Solution:

<div >How much energy do you use?</div>
<input id="q1" type="text" placeholder="# of KilaWatts"></input>
<button type="button" onclick="getInputValue();">Submit</button>
<br>
<output id="a1"></output>

<script>
  var input = document.getElementById("q1");
  var output = document.getElementById("a1");

  function getInputValue() {
    output.textContent = ((input.value * 3)   2)
  }
</script>

  • Related