-1

I just want to know where i went wrong, i tried every stack overflow answers but couldn't find one that answered my code problem

var x = document.getElementById("blah").value;
var y = document.getElementById("meow").value;
var z = x + y;

function calculate() {
  document.getElementById("frick").innerHTML = z;
}
button {
  width: 20%;
}
<input id="blah">
<input id="meow">
<button onclick="calculate()"></button>
<p id="frick"></p>
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Cinnabot
  • 40
  • 7
  • 1
    Was it absolutely necessary to name the `id` of your `p` tag as `"frick"`? – Spectric Feb 13 '21 at 02:56
  • 1
    (1) retrieve the values inside the handler, not on pageload; on pageload, they're empty (2) convert them to numbers before adding – CertainPerformance Feb 13 '21 at 02:56
  • @Spectric I thought it was hilarious due to the circumstances of my frustration, you are correct it was not needed, but i considered it not a swear word, my apologies – Cinnabot Feb 13 '21 at 03:01
  • Also: [duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+value+of+input+type+number+is+still+string) of [Input value is a string instead of a number](https://stackoverflow.com/q/27849944/4642212). – Sebastian Simon Feb 13 '21 at 03:21

1 Answers1

1

Parse the value inside the function using parseInt(). At the start, you set x to the value of the input, but at that time the input was empty. The following should work:

button {
width: 20%;
}
<html>
<body>
  <input id="blah">
  <input id="meow">
  <button onclick="calculate()">:p
  </button>
  <p id="frick">
    
  </p>
<script>
var x = document.getElementById("blah");
var y = document.getElementById("meow");
function calculate(){
var z = parseInt(x.value)+parseInt(y.value);
document.getElementById("frick").innerHTML = z;
}
</script>
</body>
</html>
Spectric
  • 30,714
  • 6
  • 20
  • 43
  • Please use `parseInt` [_with_ the second parameter, `10`](https://stackoverflow.com/q/16880327/4642212). Consider using [`Number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#Function_syntax) or [`parseFloat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat) instead, or, specifically for ``s, [`.valueAsNumber`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement#Properties). – Sebastian Simon Feb 13 '21 at 03:22