search

Home  >  Q&A  >  body text

Why can't my HTML page receive and store user input as variable data?

Consider the code I have:

var g = document.getElementById("al").value;

function start() {
  document.getElementById("test2").innerHTML = typeof(g) + parseFloat(g);
}
<p id="test2">输出在这里:</p>
<form>
  <label for="g">a:</label>
  <input type="number" id="al" name="g" placeholder="输入a" value="55">
  <button onclick="start()" type="button">这里</button>
</form>

When I click the button, the output I get is string55, no matter what the user inputs. I want to fix it and replace the 55 with the user's actual input. So what's the fix?

P粉034571623P粉034571623449 days ago548

reply all(1)I'll reply

  • P粉633733146

    P粉6337331462023-09-11 09:00:26

    You need to get the value from the function:

    function start() {
      var g = document.getElementById("al").value;
      document.getElementById("test2").innerHTML = typeof(g) + parseFloat(g);
    }
    <p id="test2">输出在这里:</p>
    <form>
      <label for="g">a:</label>
      <input type="number" id="al" name="g" placeholder="输入a" value="55">
      <button onclick="start()" type="button">这里</button>
    </form>

    reply
    0
  • Cancelreply