Joselito13
Joselito13

Reputation: 11

basic conditional with javascript

I'm trying to make an IMC calculator that shows an alert depending your IMC value. But when I try to make a conditional for show an alert depending the body-status it doesn't come

var k =
  { nombre       : 'Antonio'
  , peso         : 85
  , altura       : 1.80
  , masacorporal : function ()
    {
    var r = this.peso / (this.altura*this.altura);
    return Math.round(r*100)/100;
    }
  }
function f()
  {
  k.peso   = document.getElementById("dato1").value;
  k.altura = document.getElementById("dato2").value;
  
  document.getElementById("resultado").innerHTML = k.masacorporal();
  
  var error = 0;
  if (k.peso == '' && error == 0)
    {
    alert("El valor del peso es obligatorio");
    k.peso.focus();
    error=1;
    }
  if (k.altura=='' && error==0)
    {
    alert("El valor de la altura es obligatorio");
    k.altura.focus();
    error=1;
    }
  if (!/^([0-9])*$/.test(k.peso))
    {
    alert("El valor " + k.peso + " no es un número");
    m1.focus();
    error=1;
    }
  if (error==0)
    {
    f()
    }
  }
function m()
  {
  if (k.masacorporal < 18.5) 
    { 
    alert("Bad healt status"); 
    }
  }
PESO (kg): <input type="text" id="dato1" onkeypress=""/>
<br/>
Altura (metros): <input type="text" id="dato2"/>
<br/>
<input   type="button" value="Calcular" onclick="f()"/>
<br/>
IMC:<span id="resultado"> </span>

Thats the full code if u want to try it, for me the alert doesnt show even if i have corrected the last part

Upvotes: 0

Views: 61

Answers (2)

GirkovArpa
GirkovArpa

Reputation: 4912

You need to write masocorporal as k.masacorporal().

It has to be prefixed with k. because it's a property of k, and it has to have parentheses to execute it because it's function. Otherwise you're checking if the function is smaller than 18.5 which makes no sense; you want to compare the value the function returns.

var k = {
  nombre: "Antonio",
  peso: 0,
  altura: 1.80,
  masacorporal: function () {
    var r = this.peso / (this.altura * this.altura);
    return Math.round(r * 100) / 100;
  }
};

function m() {
  if (k.masacorporal() < 18.5) { alert("Bad health status"); }
}

m();

Upvotes: 0

Masood
Masood

Reputation: 1595

You are trying to access method inside object directly. You should add object name before method.

function m() {
    if (k.masacorporal < 18.5){alert("Bad healt status");}
}

Upvotes: 1

Related Questions