Magnus Vestergaard
Magnus Vestergaard

Reputation: 88

javascript says that 4 is higher than 16

function getNum() {
    num = $('.slicesinput').val();
    num2 = $('.numinput').val();
    if (num === "" || num2 === "") {
        alert('Your inputs may not be empty, else the diagram won\'t work proper...');
    } else {
        if (num > num2) {
            alert('Whoops, ' + num + ' is a higher number than ' + num2 + ', please fix this and try again');
        } else if (num === num2) {
            alert('Woops, ' + num + ' and ' + num2 + ' is the same number...');
        } else {
            progressBarUpdate(num, num2);
        }
    }
}

the HTML

<p>Number of slices you want</p>
<input name="slices" class="slicesinput" type="text"/>
<p>Out of max slices</p>
<input name="num" class="numinput" type="text"/>
<p>Ex. 3 + 6</p>
<input type="submit" onclick="getNum()"/>

When I submit this with ex 4 in the first and 16 in the second it pops up with an alert "Woops, 4 is a higher number than 16, please fix this and try again", but if i choose 4 and 6 it works fine..? What is the actual problem? How can I fix this?

Upvotes: 1

Views: 56

Answers (2)

Tharindu
Tharindu

Reputation: 61

When you get value of textbox like,

num = $('.slicesinput').val();

What you're getting is a string value and not a number. So what you're comparing is actually 2 strings and not numbers. You need to parse the String to a Number to make it working

num = Number($('.slicesinput').val());

Upvotes: 2

Martin Shishkov
Martin Shishkov

Reputation: 2837

Try to put your 'num' variables in a Number() function because they might be compared as strings instead of numbers. And you can also change inputs' type to number.

Upvotes: 3

Related Questions