0

I have 2 input boxes so I enter a "From" and "To" values in each. For some reason it works in with a certain range only, but can't figure out why.

var from = $('#from').val();
var to = $('#to').val();
var total = '';
for (i = from; i <= to; i++)
{
     if (i == to)
        total += i;
     else
        total += i + ',';
}
console.log(total);

so this works when doing something like 1-10 but I've tried 8-30 or 8-100 doesn't work...can't seem to figure out why..

Andres
  • 2,013
  • 6
  • 42
  • 67

1 Answers1

4

You have to explicitly turn the values (string) into numbers first, otherwise you're stuck with string comparison, i.e. '2' > '100'.

var from = +$('#from').val();
var to = +$('#to').val();

I'm using the unary + operator for that. You could also use this:

var from = parseInt($('#from').val(), 10);
var to = parseInt($('#to').val(), 10);

Refer to this answer to decide which one is better for your purposes. Personally I'd go with the first one, short and sweet :)

Community
  • 1
  • 1
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309