gingobr gingobr - 1 month ago 7
HTML Question

Javascript not showing

I'm new to JavaScript. I created this html form that calls a JS function. The function should make a simple calculation and return the total value to the HTML using innerHTML but for some reason it's not working.
Can somebody please help to find what is wrong with it? Tks!

<form id="inputInfo" name="inputInfo">

<span> Insert a value </span><br/>
<input type="number" id="value"> <br/>
<button id="send" type="submit" class="button" onclick="calculate()"> <span> Send </span></button>

<!--output from javascript-->
<p id="output1"> </p>
<p id="output2"> </p>
<p id="output3"> </p>

</form>

//** Function below is into a .js file **//

function calculate() {

var value = document.getElementById("value");
var commission;
var finalValue;
var message;

if(value <= 0){
commission = 0;
finalValue = 0;
message = "* Value is wrong! *";

} else {
commission = value < 250 ? 25 : (value * 0.1);
finalValue = value + commission;
message = "";

}

document.getElementById("output1").value.innerHTML = finalValue;
document.getElementById("output2").value.innerHTML = commission;
document.getElementById("output3").innerHTML = message;
}

Answer

The line var value = document.getElementById("value");, you are only accessing the DOM of the input. You will need to do .value in order to actually get the "value" of the input:

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

As for the output parts:

document.getElementById("output1").value.innerHTML = finalValue; document.getElementById("output2").value.innerHTML = commission; document.getElementById("output3").innerHTML = message;

Remove the .value and only use .innerHTML for these.

As with above, you are accessing the DIM with document.getElementById("output1"), and you set the innerHTML value.

Full code sample: https://jsfiddle.net/u87a7e6b/

<form id="inputInfo" name="inputInfo">

  <span> Insert a value </span>
  <br/>
  <input type="number" id="value">
  <br/>
  <button id="send" type="button" class="button" onclick="calculate()"> <span> Send </span></button>

  <!--output from javascript-->
  <p id="output1"> </p>
  <p id="output2"> </p>
  <p id="output3"> </p>

</form>

<script>
function calculate() {
  var value = document.getElementById("value").value;
  var commission;
  var finalValue;
  var message;

  if (value <= 0) {
    commission = 0;
    finalValue = 0;
    message = "* Value is wrong! *";

  } else {
    commission = value < 250 ? 25 : (value * 0.1);
    finalValue = value + commission;
    message = "";
  }

  document.getElementById("output1").innerHTML = finalValue;
  document.getElementById("output2").innerHTML = commission;
  document.getElementById("output3").innerHTML = message;
}
</script>