Reputation: 425
I am trying to given alert to the user, if user enter more than input variable value.
problem statement:
Max_ava_water = 300
if user enter a 6 also it is showing 'Enter less or Equal values'.
var Max_ava_water = 300
$('#input_rd').keyup(function() {
if ($(this).val() > Max_ava_water) {
console.log("Enter less or Equal values")
$(this).val('');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="value" id="input_rd" />
Upvotes: 0
Views: 466
Reputation: 1074148
You're checking on every keyup
event, which is too soon — the user could be trying to type 600, which starts with 6, which is less than 100. (Sorry, that comment was when I'd misread your >
as <
. But the basic idea still applies.)
Instead, check when the field loses focus (blur
) or when they try to confirm the value in some other way.
I'd strongly suggest not clearing the field when the value is too low. Instead, let them edit the value (maybe they just missed out a 0
at the end).
const Max_ava_water = 300;
// Using `blur` event
$('#input_rd').on("blur", function() {
// Explicit conversion
const value = this.value ? parseInt(this.value, 10) : NaN;
// Note that `NaN` is never `>` anything
if (value > Max_ava_water) {
console.log("Enter less or Equal values")
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="number" id="input_rd" />
Also note that type="value"
is invalid for input
fields. You could use type="number"
as I did above to trigger the browser's standard handling for number fields, perhaps with min
and max
to do range checking.
Side note: val
returns a string (or undefined
if you call it on an empty jQuery set, but you aren't). Your expression relies on >
to implicitly convert that to a number. >
does do that, but often it's better to do the conversion intentionally, not least because the rules for implicit conversion might not be the rules you want to apply (""
converts to 0
, for instance). My answer here describes your various options and their pros and cons.
Upvotes: 3