Bruno S
Bruno S

Reputation: 1

Can't make the code recognize 0 as a value

I'm making an editable RPG sheet. For this specific section, I need it to compare the 1_7, 2_7 and 3_7 to the result of the equation, and have it select the smaller value. However, while it works on most situations, it doesn't recognize 0 as a value. 1_7, 2_7 and 3_7 are inputted manually.

What should I do in order to get the code to recognize 0 as a value?

var x = 
this.getField("1_7").value;
var y = 
this.getField("2_7").value;
var z = 
this.getField("3_7").value;

var f = Math.floor((this.getField("Des Temp").value - 10) / 2);

var temp;

if(!x)
{
x = f;
}

if(!y)
{
y = f;
}

if(!z)
{
z = f;
}

if(x <= y && x <= z)
temp = x;
else if(y <= z)
temp = y;
else
temp = z;

if(f > temp)
f = temp;

if(f > 0){
event.value = "+" + f;
}
else{
event.value = f;
}

Upvotes: 0

Views: 80

Answers (2)

Ricky Notaro-Garcia
Ricky Notaro-Garcia

Reputation: 673

It's because 0 is considered as false inside a javascript comparaison. If you want to verify if the field have data, you can use the length property.

var x = 0;
var y = 5;
var z = 3;


var f = 10;

if(0)
{
  console.log("0 is false");
}

if(1)
{
  console.log("1 or any number != 0 is true");
}

if(x.length)
{
  x = f;
  console.log("x is not set");
}

if(y.length)
{
  y = f;
    console.log("y is not set");
}

if(y.length)
{
  z = f;
    console.log("z is not set");
}

Upvotes: 0

JasonB
JasonB

Reputation: 6368

O is a "falsy" value so

if(!x)

Is doing what it is supposed to do. The empty value is probably an empty string so you could do

if ( ! x.length )

instead.

$('#x').on( 'input', function() {
  console.log( ! $(this).val().length );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='x' >

Upvotes: 1

Related Questions