Jamie Blue
Jamie Blue

Reputation: 52

Issue With Javascript Generating The Wrong Numbers

I'm sorry for the title, this question is very specific to my code and I wasn't sure how to word it.

I am making a webpage which can be used to convert Miles to KM, or KM to Miles within a given range. I have two textboxes for inputs, so for example if you enter 5 and 50, it will generate a table with all the conversions of 5 miles/km to 50 miles/km depending on which conversion is chosen.

The problem is, this doesn't work if the higher number in the range given is above 10 and below the number multiplied to 10.

For example, if I were to enter 3 and 10, it would only generate a table with the conversion for 10 and not the numbers in-between. The same goes for using 3 and any number between 9 and 30, 99 and 300, 999 and 3000 and so on.

Here is the code which I'm sure must be causing the problem:

//gets values in the textboxes, used for the range of conversions
var f = document.getElementById(from).value;
var t = document.getElementById(to).value;

//finds which one is lowest and highest, stores them in appropriate variables
if(f > t) {
    max = f;
    min = t;
} else {
    max = t;
    min = f;
}

Table generation:

//Loops using the lowest number as a start for the for loop, ending only when it is less than or equal to the highest number
//Makes the table, inserting appropriate conversion numbers
//NOTE: choice is a boolean used to check whether we are converting from Miles to KM or KM to Miles
for(var i = min; i <= max; i++) {
    if(choice) {
        var row = tab.appendChild(document.createElement("tr"));
        for (var j = 0; j < 2; j++) {
            var cell = row.appendChild(document.createElement("td"));
            if(j == 0) {
                cell.appendChild(document.createTextNode(i));
            } else {
                cell.appendChild(document.createTextNode(convertToKm(i)));
            }
        }
    } else {
        var row = tab.appendChild(document.createElement("tr"));
        for (var j = 0; j < 2; j++) {
            var cell = row.appendChild(document.createElement("td"));
            if(j == 0) {
                cell.appendChild(document.createTextNode(i));
            } else {
                cell.appendChild(document.createTextNode(convertToMiles(i)));
            }
        }
    }
}

This is driving me crazy, and I'm sure it's a small mistake.

Upvotes: 1

Views: 47

Answers (1)

James Thorpe
James Thorpe

Reputation: 32202

The problem is here:

var f = document.getElementById(from).value;
var t = document.getElementById(to).value;

Both f and t will be strings as they've come from input fields, and therefore 3 is "greater than" 10 for example. You need to parse them as a number, using parseInt:

var f = parseInt(document.getElementById(from).value, 10);
var t = parseInt(document.getElementById(to).value, 10);

Upvotes: 1

Related Questions