How to invoke the function in HTML

Asked

Viewed 37 times

-2

Guys, I’m starting in JS and would like to know how I do to display the results of the product() function in html, because in console.log it works correctly (console.log(product(1, 2, 3))) Can anyone help? Thank you

function product(x, y, z) {

  var arg1 = document.getElementById('arg-1').value
  var arg2 = document.getElementById('arg-2').value
  var arg3 = document.getElementById('arg-3').value
  if (x !== undefined && y === undefined && z === undefined) {
    return x;

  } else if (x !== undefined && y !== undefined && z === undefined) {
    return x + y;
  } else if (x !== undefined && y !== undefined && z !== undefined) {
    return (x + y) / z;
  } else if (x === undefined && y === undefined && z === undefined) {
    return false;
  } else {
    return null;
  }
}

console.log(product(1, 2, 3))
<input type="number" id="arg-1">
<input type="number" id="arg-2">
<input type="number" id="arg-2">
<button onclick="product()">Submit</button>
<p id="saida"></p>

1 answer

1


Opa Thiago, for you to display this in html, you need to give a innerHTML in the div you want to display the result.

function product(x, y, z) {
    if (x !== undefined && y === undefined && z === undefined) {
        return x;

    } else if (x !== undefined && y !== undefined && z === undefined) {
        return x + y;
    } else if (x !== undefined && y !== undefined && z !== undefined) {
        return (x + y) / z;
    } else if (x === undefined && y === undefined && z === undefined) {
        return false;
    } else {
        return null;
    }
}
var saida = document.getElementById('saida') // pega a div

var valor = product(1, 2, 3) // armazena o valor
saida.innerHTML = valor //exibe o valor
<p id="saida"></p>

I also noticed in your code that you are declaring the variable arg3 erroneously referenced the id arg-2

If you want, and clearly want, to pass the values of the inputs instead of hammering them, you will have to do a treatment also when reading these values, a Number or parseFloat solve your life.

I hope I’ve helped!!

  • Oops, dude really helped was that, thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.