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???
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-
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
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="" />
You need to use type="number"
to make the script work:
<input id="start" type="number" value="" />
<input id="end" type="number" value="" />
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
}
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
})
You have to type cast the value to int just like
if (parseInt($("#end").val()) > parseInt($("#start").val())) {
//do something
}else {
alert('Wrong Input');
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.