...

View Full Version : Set a Null Input to Zero



ccarrin2
01-02-2012, 04:11 PM
I'm guessing this question will be one of the easiest questions ever posted but I'm just not getting this fix. I have a simple Javascript program that calculates a users pace for their run. The inputs are done through an HTML Form.

The user can input hours, minutes, & seconds of their run. Then the distance number & measurment. Then finally the pace desired. I am having some trouble with null values in this program. If I input a 0 in hours and then fill everything out the program works great. 100%! But, if I leave the field blank and hit calculate I get a NaN. I'm guessing I need some kind of statement like if this value is null set it to zero but I am not having any luck with exactly what kind of syntax I need. So here is the code, again not very complex, any help would be greatly appreciated!


function calculateTime(){
var time_hour = parseInt(document.getElementById("time_hour").value);
var time_min = parseInt(document.getElementById("time_minute").value);
var time_sec = parseFloat(document.getElementById("time_second").value);
var dist_num = parseFloat(document.getElementById("dist_num").value);
var pace_choice = document.getElementById("pace_choice").selectedIndex;
var dist_choice = document.getElementById("dist_choice").selectedIndex;
var total_sec = (time_hour * 3600) + (time_min * 60) + (time_sec);

// Then I'm guessing my if statement would go here somewhere?

ccarrin2
01-02-2012, 04:36 PM
Here is the pace calculator! As you will see if you fill in all values everything works fine. But if you leave hour blank NaN

http://www.gmustudent.com/calc.html

Amphiluke
01-02-2012, 05:28 PM
This example should help:


var t = "";
parseInt(t); // NaN
parseInt(+t); // 0

Note that the unary "+" operator returns its operand transformed into a number.

ccarrin2
01-02-2012, 08:57 PM
This example should help:


var t = "";
parseInt(t); // NaN
parseInt(+t); // 0

Note that the unary "+" operator returns its operand transformed into a number.

So in order to do what you are saying should I replace t with time_hour in order to set it to 0?

Old Pedant
01-02-2012, 10:06 PM
Not quite.



var time_hour = parseInt(+document.getElementById("time_hour").value);

But you could also be more explicit about it:


var time_hour = parseInt(document.getElementById("time_hour").value);
if ( isNaN(time_hour) ) time_hour = 0;

ccarrin2
01-02-2012, 11:55 PM
Not quite.



var time_hour = parseInt(+document.getElementById("time_hour").value);

But you could also be more explicit about it:


var time_hour = parseInt(document.getElementById("time_hour").value);
if ( isNaN(time_hour) ) time_hour = 0;


WOW Thank you so much!!! This was my first question ever on a forum and it was awesome! Thank you again!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum