Richa
Richa

Reputation: 3289

Compare values in two input fields

I have two input fields and i am wondering how do i compare value's between these two fields.

<input id="start" type="numeric" value="" />

        <input id="end" type="numeric" value="" />

In above input fields, if the value in input field with id='start' is greater than id='end', i want to display an alert.

I tried below but not working

    if ($("#end").val()  > $("#start").val()) {

            //do something

    }else {
            alert('Wrong Input');
        }

What am i doing wrong???

Upvotes: 0

Views: 3040

Answers (6)

Mahdi Sahib
Mahdi Sahib

Reputation: 120

you can't use type="numeric" to make input numeric only

to solve this proplem use this code

HTML

<input type="tel" name="name">

jQuery

    // HTML Text Input allow only Numeric input
    $('[type=tel]').on('change', function(e) {
        $(e.target).val($(e.target).val().replace(/[^\d\.]/g, ''))
    })
    $('[type=tel]').on('keypress', function(e) {
        keys = ['0','1','2','3','4','5','6','7','8','9','.']
        return keys.indexOf(event.key) > -1
    })

Upvotes: 1

Govind Singh
Govind Singh

Reputation: 15490

you are comparing strings $("#end").val() > $("#start").val() so you have to compare in numbers, and dont forget about the radix

if(parseInt($("#end").val(),10)  > parseInt($("#start").val(),10))

and type="numeric" is a wrong syntax, use type="number"

<input id="start" type="number" value="" />

Upvotes: 2

Milind Anantwar
Milind Anantwar

Reputation: 82231

You need to use type="number" to make the script work:

<input id="start" type="number" value="" />
<input id="end" type="number" value="" />

Demo

Or you can use input type text and then parse the input using parseInt(val) and compare them. somethink like this:

if (parseInt($("#end").val()) > parseInt($("#start").val())){
   //rest code
}

Upvotes: 1

Visruth
Visruth

Reputation: 3450

You have to type cast the value to int just like

if (parseInt($("#end").val())  > parseInt($("#start").val())) {

            //do something

    }else {
            alert('Wrong Input');
        }

Upvotes: 0

halkujabra
halkujabra

Reputation: 2942

You should bind an event handler such as 'keypress' to one of the fields. When that even is triggered, you should compare the values of both the input fields and show alert if necessary.

Additionally, type="number" is correct not "numeric" .

Here's a working fiddle-

http://jsfiddle.net/pe2ZE/

Upvotes: 4

Satpal
Satpal

Reputation: 133403

Use type="number", As per my knowledge there is type as such numeric

Code

if (+$("#end").val() > +$("#start").val()) {
    //do something
} else {
    alert('Wrong Input');
}

Here I have use + to convert value to integer

Upvotes: 2

Related Questions