Shamss Zaidan
Shamss Zaidan

Reputation: 625

Convert time to decimal using Jquery

I want to convert the time (min:sec:hs) to decimal. Before the comma are for the seconds and after the comma are for Fractional Seconds. Something like: 02:10:55 = 130,55 (2*60 + 10) & (.55)

HTML

<form>
Min: <input type="number" id="min" onkeyup="myFunction()">
Sec: <input type="number" id="sec" onkeyup="myFunction()">
Hon: <input type="number" id="hon" onkeyup="myFunction()">
<p class="result"></p> 
</form>

JQUERY

<script type="text/javascript">
function myFunction() {
var num1 = $("input[id='min']").val(),
num2 = $("input[id='sec']").val(),
num3 = $("input[id='hon']").val(),
result = parseInt(num1) * 60 + parseInt(num2);
$(".result").text(result);
}
</script>

Thanks to @Andrew Brooke I solved it with this code:

result = parseInt(num1) * 60 + parseInt(num2) + "." + parseInt(num3)

Now I have another problem. I want to get the results even If I fill only one fields. Now I get NaN if one of the field is empty.

Any help will be appreciated. Thanks in advance,

Upvotes: 2

Views: 1885

Answers (2)

Nicholas
Nicholas

Reputation: 486

A more concise way is to use Number(), which will return 0 when passed the empty string. As a side note, I would rename your variables to make it more readable, and use $("#min") instead of $("input[id='min']")

var hon = Number($("#hon").val()),
    min = Number($("#min").val()),
    sec = Number($("#sec").val());

You also want to convert sec to decimal, right? You can do that with sec / 60. Thus, you should calculate result with:

var result = hon + min * 60 + sec / 60;

Upvotes: 1

Andrew Brooke
Andrew Brooke

Reputation: 12173

For the first problem, you can just concatenate your string with a comma

result = parseInt(num1) * 60 + parseInt(num2) + "," + parseInt(num3);

For the second problem, an easy solution would be to check if the textboxes are empty, and give num1, num2, or num3 a value of 0 if so. Like this

var num1 = $("input[id='min']").val() != "" ? $("input[id='min']").val() : 0,
    num2 = $("input[id='sec']").val() != "" ? $("input[id='sec']").val() : 0,
    num3 = $("input[id='hon']").val() != "" ? $("input[id='hon']").val() : 0,
...

Upvotes: 1

Related Questions