-1

So I want to access the result of a function that is triggerd by clicking a button. Right now, the result of the function, named CalculaIMC, is shown in an alert, but I'd like to do something else with it, so I tried storing it in a new variable, named result, but it doesn't work. Can anyone help me? Thanks.

function calculaIMC (peso, altura){
    imc = peso/(altura * altura) * 10000
    if(imc <= 18.5){
        return `Tu IMC es ${imc.toFixed(1)}, lo que se considera un peso insuficiente, por debajo del IMC mínimo de 18.5`
    }else if(imc > 18.5 && imc <=24.9){
        return `Tu IMC es ${imc.toFixed(1)}, lo que se considera un peso normal`
    }else if(imc > 24.9 && imc <=26.9){
        return `Tu IMC es ${imc.toFixed(1)}, lo que se considera un sobrepeso de grado 1`
    }else if(imc > 26.9 && imc <=29.9){
        return `Tu IMC es ${imc.toFixed(1)}, lo que se considera un sobrepeso de grado 2`
    }else if(imc > 29.9 && imc <=34.9){
        return `Tu IMC es ${imc.toFixed(1)}, lo que se considera una obesidad de grado 1`
    }else if(imc > 34.9 && imc <=39.9){
        return `Tu IMC es ${imc.toFixed(1)}, lo que se considera una obesidad de grado 2`
    }else if(imc > 39.9 && imc <=49.9){
        return `Tu IMC es ${imc.toFixed(1)}, lo que se considera obesidad mórbida`
    }else if(imc > 49.9){
        return `Tu IMC es ${imc.toFixed(1)}, lo que se considera obesidad extrema`
    }else{
        return `Ha habido un error con los datos. Por favor, introduce tu peso en centímetros y tu altura en kilos. Utiliza un punto para separar las decimales (por ejemplo: 72.5)`
    }

}

const botonInfo = document.querySelector("#begin")
botonInfo.addEventListener("click", () => {
    var getPeso = parseFloat (prompt("Introduce tu peso en kilos"))
    var getAltura = parseFloat (prompt("Introduce tu altura en centímetros"))
    alert (calculaIMC(getPeso,getAltura))
    console.log(calculaIMC (getPeso,getAltura))

})

var result = calculaIMC(getPeso,getAltura)//this doesn't work.
David
  • 208,112
  • 36
  • 198
  • 279
cmarlar
  • 1
  • 1
  • 1
    What "doesn't work" about it? When you debug, what specific problem do you observe? *At a glance* it looks like you haven't defined the variables `getPeso` or `getAltura` used on that last line of code, and your browser's development console would be showing an error indicating exactly that. Though the code provided, as-is, fails before it even reaches that part. – David Sep 26 '22 at 15:36
  • 1
    If you use a snippet then please have a look at the editor before you put your JavaScript in a section labeled "HTML". And also _test_ your snippet before you post it. – Andreas Sep 26 '22 at 15:36
  • You're trying to use variables (`calculaIMC(getPeso,getAltura)`) that don't exist yet (`botonInfo.addEventListener("click", () => { var getPeso = ... var getAltura = ...`). Why do you call `calculaIMC()` at all with those non-existing variables as arguments? – Andreas Sep 26 '22 at 15:44
  • Hi @David. Exactly, my question is: how can I store the getPeso and getAltura in a new variable? Sorry if I didn't express myself correctly, English is not my native language and I'm a beginer on JS. – cmarlar Sep 26 '22 at 15:44
  • @cmarlar: They're currently defined inside of a function, but you're trying to use them outside of that function. Define them in the scope where you need them... outside of the function. – David Sep 26 '22 at 15:46
  • Hi @Andreas, so should i define the variables beforehand? How, since they are defined by the user where de prompt appears. That is what I don't understand. How can I take the result of the function calculaIMC executed inside the event listener and store it outside? – cmarlar Sep 26 '22 at 15:49
  • Not by calling the function outside of that event handler with variables only available in the event handler. Have a look at [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) <- They talk about AJAX but the problem is the same: "return" the value of an asynchronous function (in this case the event handler) – Andreas Sep 26 '22 at 15:50
  • @David, yes, I understand that, but I don't know how to do it. I tried storing them inside of var result, as some answers in StackOverflow suggest, but this doesn't work. How, exactly, can I do that? – cmarlar Sep 26 '22 at 15:51

1 Answers1

0

On your last line of code you're trying to use the variables getPeso and getAltura, which don't exist in that scope. (They exist inside of a function, but not outside of that function.)

Ignoring the event handler for the moment, since you're trying to calculate a result immediately upon loading the page... You essentially just forgot to define and initialize those two values. Define them before using them:

function calculaIMC (peso, altura){
    imc = peso/(altura * altura) * 10000
    if(imc <= 18.5){
        return `Tu IMC es ${imc.toFixed(1)}, lo que se considera un peso insuficiente, por debajo del IMC mínimo de 18.5`
    }else if(imc > 18.5 && imc <=24.9){
        return `Tu IMC es ${imc.toFixed(1)}, lo que se considera un peso normal`
    }else if(imc > 24.9 && imc <=26.9){
        return `Tu IMC es ${imc.toFixed(1)}, lo que se considera un sobrepeso de grado 1`
    }else if(imc > 26.9 && imc <=29.9){
        return `Tu IMC es ${imc.toFixed(1)}, lo que se considera un sobrepeso de grado 2`
    }else if(imc > 29.9 && imc <=34.9){
        return `Tu IMC es ${imc.toFixed(1)}, lo que se considera una obesidad de grado 1`
    }else if(imc > 34.9 && imc <=39.9){
        return `Tu IMC es ${imc.toFixed(1)}, lo que se considera una obesidad de grado 2`
    }else if(imc > 39.9 && imc <=49.9){
        return `Tu IMC es ${imc.toFixed(1)}, lo que se considera obesidad mórbida`
    }else if(imc > 49.9){
        return `Tu IMC es ${imc.toFixed(1)}, lo que se considera obesidad extrema`
    }else{
        return `Ha habido un error con los datos. Por favor, introduce tu peso en centímetros y tu altura en kilos. Utiliza un punto para separar las decimales (por ejemplo: 72.5)`
    }

}

var getPeso = parseFloat (prompt("Introduce tu peso en kilos"))
var getAltura = parseFloat (prompt("Introduce tu altura en centímetros"))
var result = calculaIMC(getPeso,getAltura)//this does work.
console.log(result);

UPDATE: Based on comments, it sounds like what you want is still to calculate the value in response to a button click, you just want the value available in global scope so you can use it for other purposes later.

You already have the part about defining the value in global scope:

var result = calculaIMC(getPeso,getAltura)

But if you don't want to calculate the value there, then don't calculate the value there:

var result;

Simply update the value in the function:

result = calculaIMC(getPeso,getAltura)

Then you can use that value later. For example:

function calculaIMC (peso, altura){
    imc = peso/(altura * altura) * 10000
    if(imc <= 18.5){
        return `Tu IMC es ${imc.toFixed(1)}, lo que se considera un peso insuficiente, por debajo del IMC mínimo de 18.5`
    }else if(imc > 18.5 && imc <=24.9){
        return `Tu IMC es ${imc.toFixed(1)}, lo que se considera un peso normal`
    }else if(imc > 24.9 && imc <=26.9){
        return `Tu IMC es ${imc.toFixed(1)}, lo que se considera un sobrepeso de grado 1`
    }else if(imc > 26.9 && imc <=29.9){
        return `Tu IMC es ${imc.toFixed(1)}, lo que se considera un sobrepeso de grado 2`
    }else if(imc > 29.9 && imc <=34.9){
        return `Tu IMC es ${imc.toFixed(1)}, lo que se considera una obesidad de grado 1`
    }else if(imc > 34.9 && imc <=39.9){
        return `Tu IMC es ${imc.toFixed(1)}, lo que se considera una obesidad de grado 2`
    }else if(imc > 39.9 && imc <=49.9){
        return `Tu IMC es ${imc.toFixed(1)}, lo que se considera obesidad mórbida`
    }else if(imc > 49.9){
        return `Tu IMC es ${imc.toFixed(1)}, lo que se considera obesidad extrema`
    }else{
        return `Ha habido un error con los datos. Por favor, introduce tu peso en centímetros y tu altura en kilos. Utiliza un punto para separar las decimales (por ejemplo: 72.5)`
    }

}

var result;

const botonInfo = document.querySelector("#begin")
botonInfo.addEventListener("click", () => {
    var getPeso = parseFloat (prompt("Introduce tu peso en kilos"))
    var getAltura = parseFloat (prompt("Introduce tu altura en centímetros"))
    result = calculaIMC(getPeso,getAltura)
})

document.querySelector("#test").addEventListener("click", () => {
    console.log(result);
})
<button id="begin">begin</button>
<button id="test">test</button>
David
  • 208,112
  • 36
  • 198
  • 279
  • Thank you so much. I'm going to try this. At this point I was doing var peso = getPeso to use peso, but still didn't work. Thank you, so much – cmarlar Sep 26 '22 at 16:09
  • Hello again, @David. This would be the solution, but as you say, this calculates the result inmediately upon loading the page, which is not in my requirements. My requirement is to trigger the prompts by clicking a button. How would I do it keeping that in mind? Is there a way to do something like: "peso = getPeso?" or something like that? – cmarlar Sep 26 '22 at 16:21
  • @cmarlar: Your original code already does that. Just take out the last line that "doesn't work". Assuming the HTML is correct (which isn't included in the question), that code [already works](https://jsfiddle.net/kf9d5su2/). – David Sep 26 '22 at 16:38
  • @cmarlar: I've updated the answer with another concept that you may be looking for. You can define the variable in global scope, set its value in your button click handler, then use that value at any later time (such as in another button click handler). – David Sep 26 '22 at 16:51