ak85
ak85

Reputation: 4264

check which input field has a greater value on keyup

I want to output in a list which of the two input fields value is higher if both fields have a value in it.

This seems to work except that I also want to compare 0 value. Right now, if I try with 0 and 99, nothing happens because .input1 isn't true. Also, is there a better way to do something like this if I have more fields to compare? I don't want to have the browser crash if keyup is constantly being checked.

My HTML:

<input title="input 1" type="tel" class="input1" value="" maxlength="3" />
<input title="input 2" type="tel" class="input2" value="" maxlength="3" />
<ul></ul>

My JavaScript:

var input1 = '';
var input2 = '';
var input1Title = '';
var input2Title = '';

$("input").keyup(function () {
    input1 = parseInt($('.input1').val(), 10) || 0;
    input1Title = $('.input1').attr("title");
    input2 = parseInt($('.input2').val(), 10) || 0;
    input2Title = $('.input2').attr("title");

    if (input1 && input2) {
        var description = '';

        if (input1 > input2) {
            description = input1Title + ' is greater than ' + input2Title;
        } else if (input1 < input2) {
            description = input1Title + ' is less than ' + input2Title;
        } else {
            description = input1Title + ' is the same ' + input2Title;
        }

        $("ul").append("<li>" + description + "</li>");
    }
});

See my JSFiddle: http://jsfiddle.net/C5pgc/

Upvotes: 1

Views: 1528

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

You are forcing the values to 0 if the field is empty. Your condition then checks input1 && input2, which will fail because in JS 0 equates to false. As you are coercing the values to zero anyway, you don't need that condition.

$("input").keyup(function () {
    input1 = parseInt($('.input1').val(), 10) || 0;
    input1Title = $('.input1').attr("title");
    input2 = parseInt($('.input2').val(), 10) || 0;
    input2Title = $('.input2').attr("title");

    var result = '';
    if (input1 > input2) {
        result = ' is greater than ';
    } else if (input1 < input2) {
        result = ' is less than ';
    } else {
        result = ' is the same ';
    }
    $("ul").append("<li>" + input1Title + result + input2Title + "</li>");
});

Example fiddle

Note I also DRY'd up the last part a little.

Upvotes: 4

Danny B
Danny B

Reputation: 206

You could try adding two extra if's. One asking if input1 is equal to 0 and input2 is more than 0 then the same again vice versa.

Upvotes: 0

Related Questions