1

Consider the code I have:

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

function start() {
  document.getElementById("test2").innerHTML = typeof(g) + parseFloat(g);
}
<p id="test2">Output is here:</p>
<form>
  <label for="g">a:</label>
  <input type="number" id="al" name="g" placeholder="Enter a" value="55">
  <button onclick="start()" type="button">Here</button>
</form>

The output I get on clicking the button is string55, whatever the user input is. I want to fix it and replace 55 with user's actual input. What is the fix then?

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
M.Riyan
  • 79
  • 5
  • You have nothing in your script storing the data. – G-Cyrillus Jul 04 '23 at 17:33
  • Inline event handlers like `onclick` are [bad practice](/q/11737873/4642212). They’re an [obsolete, cumbersome, and unintuitive](/a/43459991/4642212) way to listen for events. Always [use `addEventListener`](//developer.mozilla.org/en/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead. – Sebastian Simon Jul 04 '23 at 17:38

1 Answers1

1

You need to grab the value from within the function:

function start() {
  var g = document.getElementById("al").value;
  document.getElementById("test2").innerHTML = typeof(g) + parseFloat(g);
}
<p id="test2">Output is here:</p>
<form>
  <label for="g">a:</label>
  <input type="number" id="al" name="g" placeholder="Enter a" value="55">
  <button onclick="start()" type="button">Here</button>
</form>

PS, using inline HTML on* handlers is considered bad programming habit. It's hard to debug. JS should be in one place only, instead, use Element.addEventListener()

const elBtn = document.querySelector("#start");
const elTest = document.querySelector("#test2");
const elG = document.querySelector("[name=g]");

const printGValue = () => {
  const g = elG.value;
  elTest.textContent = typeof(g) + parseFloat(g);
};

// Do on click
elBtn.addEventListener("click", printGValue);
// And on init:
printGValue();
<form>
  <label>
    a: <input type="number" name="g" placeholder="Enter a" value="55">
  </label>
  <button id="start" type="button">Here</button>
</form>

<p id="test2"></p>
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313