Enter less than or equal value using Javascript - javascript

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" />

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.

Related

How do I detect whether or not an input with type=time has any values entered

I have a javascript script that's supposed to detect whenever an html form input with type="time" has any value entered.
However, whenever I enter a partial value (for instance, type one number, instead of a full time with AM/PM), it doesn't detect the input as having a value.
In the below example, timeSelector is the input with type="time".
if (timeSelector.value == "") {
timeSelector.classList.add("empty");
} else {
timeSelector.classList.remove("empty");
}
Is there any way to detect this type of thing?
To clarify, since apparently I didn't ask my question clearly enough, I need to detect when a time input has something entered, even if that something is an invalid or incomplete input.
Well the problem with html5 inputs is they do not give the text in the input if it is not valid. So you can use checkValidity when the user removes focus from the element.
var checkInput = function() {
var value = this.value
var isValid = this.checkValidity()
if (!this.value.length && isValid) {
console.log('empty');
} else if (!this.value.length && !isValid) {
console.log('invalid time entered')
} else {
console.log('valid time entered')
}
}
var input = document.querySelector("input")
input.addEventListener("input", checkInput)
input.addEventListener("blur", checkInput)
<input type="time" />
Per the specification on Input Elements with type time ( HTML Spec ) :
The value attribute, if specified and not empty, must have a value that is a valid time string.
If the value of the element is not a valid time string, then set it to the empty string instead.
This means that input and change events don't occur until the entire time field has been filled out. Why? Because nothing really has changed.
You may think that you can circumvent this by using keydown or keyup events, but this is simply not the case.
The value is not changed and is therefore inaccessible until a full string that is capable of being parsed as a time is inside the time input box.
By filling in the below example you can see how the events fire. Notice the lack of value until everything is filled in.
let i = document.querySelector("input"),
on = type => i.addEventListener(type, function() { console.log(`${type}, value: ${i.value}`); });
on("keydown");
on("keyup");
on("change");
on("input");
<input type="time">
The only way to possibly get around the lack of a changing value is to set a default value as below:
let i = document.querySelector("input"),
on = type => i.addEventListener(type, function() { console.log(`${type}, value: ${i.value}`); });
on("change");
<input type="time" value="00:00">
However, with a default value there is a risk that the user will submit a time that isn't something that you'd likely want.
You could write some validation code to take care of this depending on the complexity of your functionality this may be possible.
Overall if this is something you need and the functionality is a bit more complicated than you think you can handle validating yourself, it would be best to either create your own time input interface from other input types, or to use a library or UI kit from a source that has already done the legwork.

How to check for the multiple dots and stop to enter multiple dot using javascript?

I am having a input type text.
<input type="text" class="checkForDot" />
What i am trying to do is, when a user enters numbers into the box then find for the "." in the field, if it contains more then one ".", then prevent it to enter another "." in the text field.
my jquery code is:
$(".checkForDot").on("keyup", function (event) {
CheckForDot($(this).val());
});
function CheckForDot(value) {
if (value != null || value != '') {
var str = value.toString();
if (str.indexOf('.', str.indexOf('.') + 1) != -1) {
console.log("ok");
}
}
}
It is working fine, if two "." enters into the text box, but how to prevent to enter multiple "." in the text field?
If any other approach better than this please tell.
$(document).ready(function() {
var original='';
$('.checkForDot').on('input', function() {
if ($(this).val().replace(/[^.]/g, "").length > 1){
$(this).val(original);
}else{
original = $(this).val();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' class='checkForDot' />
Try to use this regex to find how many dots you got in string.
If you are looking to make a field that only allows for numbers, you should consider using an input of type="number" as they will only allow for valid number characters to by added to its value. In some cases, it might even bring a different visual keyboard to ease of filling, wich is better for accessibility and UX. The number input field will, by default allow for mutliple dots, wich is annoying and is a bit harder to prevent than in a text field so it's a case of figuring wether accessibility and your UX is more important than adding a few extra lines of Javascript.
A lot of people will tell you that it is bad practice to limit keyboard actions, and they are right. when you do a preventDefault() on everything but numbers and ".", you disable tabing through form fields, the browser alt menu, any ctrl shortcuts, anything that happens within the browser.
This solution is simple and will only allow one dot in the number field. It doesn't prevent from clicking back in the number and adding numbers before the ".". It doesn't prevent from executing browser keyboard shortcuts like refresh, copy and pasting, as long as the pasted value is a valid number. It will allow to add "." withing the body of the number.
The only behavior that can't be prevented is if the user press the dot key at the end of the input repeatedly, the dot will blink on and off. This happens because of the way the number field handles its value. Wen the user types a dot at the end of a number like "13.", javascript can only retreive "13" when looking at its value as long as no decimal number have been placed. If the user typed a dot again, the value of "13.." would not be a valid number and therefore javascript woudl retreive "". This ensure you eighter get a valid number or nothing at all. In my solution, if a value returns "" without the press of backspace, delete or cut, it gets rolled back to the last valid value, wich in my example was "13", obtained from the typed value "13.". Preventing this behavior seems practically impossible and isn't a deal breaker as you get ensured your field value is always a valid, single dot number.
let lastValidInputValue;
let selectedDot = false;
const onKeypress = (e) => {
if (e.key === "." && e.target.value.indexOf(".") !== -1 && !selectedDot) e.preventDefault();
selectedDot = false;
};
const onInput = (e) => {
if (e.target.value !== "") {
lastValidInputValue = e.target.value;
} else if (e.inputType.match(/delete/g)) {
lastValidInputValue = "";
} else {
e.target.value = lastValidInputValue;
}
};
const onSelect = (e) => {
selectedDot = (window.getSelection().toString().indexOf(".") > -1)? true : false;
}
<input type="number" id="myNumber" name="myNumber" step="any" onkeypress="onKeypress(event)" oninput="onInput(event)" onselect="onSelect(event)">
You can find very detailed comments and extra bits in this Codepen

How to get "real" value from input[type=number]

If I have input[type=number], Chrome allows me to type not just numbers, but also characters like - (minus sign) - for negative numbers. And it seems you can actually type multiple of those - minus signs and dots, e.g.: ".....---888". And when that happens, in on-change event, property of event.target.value would be an empty string (because it's not a valid number). But I would like validation message to appear, telling user has to type an actual number.
So the question is: How do I read the actual value, the one that's being displayed in the input field, because it seems, sometimes it's not the same as event.target.value
I don't know if this matters - this is in a React app
You can use the event.target.validity.valid or even better the event.target.validity.badInput property to check if the value is valid.
(although badInput does not seem to be supported by IE)
But i would use the input event instead of the change event, because if the user enters invalid input when starting at an empty <input> element, the change event will not fire since the value is considered empty (due to it being invalid)
Alternatively, you could use the css :invalid selector and use it to show a message that is hidden (requires specific html structure)
input[type="number"] ~ span.message{display:none;}
input[type="number"]:invalid ~ span.message{display:block;}
Use a hidden input that mimics your [type=number] one:
var numberInput = document.querySelector('input[type=number]');
var dolly = document.querySelector('input[hidden]');
numberInput.addEventListener('keyup', (event) => {
if (event.key !== 'Backspace') {
dolly.value += event.key;
} else {
dolly.value = dolly.value.substr(0, dolly.value.length - 1);
}
console.log(dolly.value);
});
<input type="number">
<input hidden>
Obviously, you will need to do more processing for certain keys. This way you get the benefits of the number type and also maintain whatever crazy stuff the user puts in there.
I'm not sure about getting the value, but since you want to set a custom validation message, you can use input setCustomValidity property (see the docs here) and check if an input is valid using the validity.valid property. Here's my implementation.
var myInput = document.getElementById("my-input");
myInput.addEventListener("keyup", function (event) {
if (!myInput.validity.valid) {
myInput.setCustomValidity("I expect a valid number, darling!");
} else {
myInput.setCustomValidity("");
}
});
<form>
<label>Please provide me a number</label>
<input type="number" id="my-input" name="my-input">
<button>Submit</button>
</form>
update:
input[type=number] will always return empty if not number, use input[type=text]and check the value if Not-a-number using isNaN()

limiting input field (type=number) to 1 to 20

I have an input field:
<input id="thing" type='number' placeholder='Up to 20 tickets' min='1' max='20' name='tickets'>
And despite the fact that I've listed min and max numbers, it still accepts typing random letters into the field, and such.
I'd like to only allow numbers 1 to 20 to appear in the field upon user input of any kind. How might I do that?
'input' DOM event?
some HTML form magic?
Update Haaa, okay, so dynamically created form inputs don't function like normal inputs. The value fields aren't hooked up to user actions.
Never trust user's input. Limiting values in html input is only for user's convenience. Even if you somehow limited user's ability to change input value directly, he could still press f12 (in Chrome), and manually change values to whatever he wants.
That being said, your code works just fine, and does what you want it to do- it limits user to input just numbers, between 1 and 20. Before doing anything with this data though, you have to validate it on the server, so server will make sure if it's really a number, and it's really between 1 and 20, because as I said- there's no way to prevent user from entering literally anything he wants into inputs.
Using Chrome
document.querySelector( "input" ).addEventListener( "input", function( evt ) {
var v = evt.target.value;
if ( v ) {
console.log( v ); // Only outputs numbers
}
}, false );
<input type="number" value="1" min="1" max="20" name="foo" placeholder="bar">
Behaviour is as expected; nothing but numbers 1-20 are output.
You can use Plain Javascript.
<script>
function handleChange(input) {
if ((input.value < 0) && ((input.value > 20))
return false;
}
</script>
HTMl code
<input type="number" onchange="handleChange(this);" />
Or you can use this
<input type="number" onKeyPress="if(this.value.length>20) return false;" />
I ended up doing this:
var temp = ''
input.addEventListener('input', function (event) {
if (this.value == '') return
if (this.value < 1 || this.value > 20 || this.value.match(/\D/)) return this.value = temp
temp = this.value
}, false)
The input event is the most broad. It captures copy pastes, and all other manner of changing field values.
The check for empty string is important, because if some one has typed 15, and changes their mind, and wants to type 20, they'll need to backspace twice, before typing the 2 and the 0. So, the state of empty is valid.
Anytime the function runs it stores the new value in a temp var, and we apply that immediately if we get input we don't like, because preventDefault() doesn't work with the input event.

Only-numerics in Input

I currently have a snippet that only allows numbers to be typed into an input:
$('input').bind('keypress', function(event) {
var charCode = event.which;
var keyChar = String.fromCharCode(charCode);
return /[0-9]/.test(keyChar);
});
jsFiddle: http://jsfiddle.net/wgsPr/
How can I adjust this to prevent typing in numbers greater than 500?
For example, if a user types 50, then types a 1 after, it won't display the 1. However if the user types a 0 after, it will display 500. And the same goes for if a user tries to type 968 it will not show the 8, it will only show 96.
Hopefully this makes sense.
The line would be
return /\d/.test(keyChar) && parseInt(this.value+keyChar, 10) <= 500;
(Demo)
However, I still suggest not to hook on and preventDefault of keypress events - go for keyup and change events and show error messages if the input's value is invalid. Or use a HTML5 <input type="number" /> with min and max attributes.
You really should not use such methods. This works far better:
<input type="number" min="0" max="500" />
However, if you insist, take your existing code and replace the return line with:
return /\d/.test(keyChar) && this.value <= 500;
if ($(this).val() > 500) {
$(this).val($(this).val().substr(0, $(this).val().length - 1));
return false;
}
I went ahead and attempted to solve this myself, which works. Basically, it checks the value and remove the last character in the case that it makes the entire input value larger than 500. Please let me know if anything should be modified.

Categories

Resources