How to prevent input field from accepting values grater than max value - javascript

I want to stop taking input if value is greater than max value. if i use keypress event then i can achieve this by returning false if value is greater than max value. but problem is keypress doesnt give latest value. and if i use keyup then return false does not work.
<div><input type="number" allowNumbersOnly value="" (keypress)="keypress($event)" (keyup)="onKey($event)" [(ngModel)]=""/></div>
below code works but does not give latest updated value:
keypress(event){
if(event.target.value > 500){
return false;
}
}
and this gives latest updated value but return false does not work here:
onKey(event){
if(event.target.value > 500){
return false;
}
}

I did this like this.
document.getElementsByClassName('edit-items'[0].oninput = function () {
var max = parseInt(this.max);
if (parseInt(this.value) > max) {
this.value = max;
}
}
<input type="number" class="edit-items" max='10'/>

You can't prevent the default behaviour of keyup, it gets fired when user releases the key that mean when the default action has already been performed.
However you can slice the entered last value when user enter value greater than 500.
Like this:
keyUp(event) {
if (event.target.value > 500) {
let length = event.target.value.length;
event.target.value = event.target.value.slice(0, length - 1);
return false;
}
}
In html:
<input type="number" maxlength="3" (keyup)="keyUp($event)">

In additon to Priyesha's answer, you have to put the max="500" attribute into input elemnt to prevent the value to be increased via inout up arrow.
<input type="number" allowNumbersOnly value="" (keyup)="onKey($event)" max="500"/>

Related

js onkeypress not working until next input

I am trying to insert a hyphen when the input size is exactly two.
Here is my code
document.getElementById('numberInput').onkeypress = function() {
if (this.value.length == 2) {
this.value = this.value + '-';
}
}
<input type="text" id="numberInput">
But the problem is the - doesn't appears until third character is inputted. Although the hyphen is placed properly, i mean after two characters.
How can i get hyphen right after entering two characters?
I tried onkeyup but the problem is it also fires when i press backspace button. When there are two characters, the hyphen appears but at that point if I press backspace and delete the hyphen it immediately comes back. So i choose onkeypress
the value of the input text box, during onKeyPress is always the value before the change. This allows the event listener to cancel the keypress.
To get the value after the field value has been updated, schedule a function to run on the next event loop. The usual way to do this is to call setTimeout with a timeout of 0:
document.getElementById('numberInput').onkeypress = function() {
// arrow function keeps scope
setTimeout(() => {
// now it is the value after the keypress
if (this.value.length == 2) {
this.value = this.value + '-';
}
}, 0);
}
<input type="text" id="numberInput">
Why not hook onto the input event instead?
document.getElementById("numberInput")
.addEventListener("input", function(e) {
if (e.target.length === 2) {
e.target.value += "-";
}
});
This is happening because of event loop. this.value is updated only after key press. So in this case you always end up with old state.
I would recommend using other listener method, in this case oninput.
And retrieving latest input value throughout function parameters
In your case fix would be:
document.getElementById('numberInput').oninput = function (event) {
if (event.target.value.length === 2) {
this.value = event.target.value + '-'
}
}

How to keep focus after validation when use tab key

I have input text fields in jsp, and I use onChange="validation(this);" to check if null input and so on, but when I use tab key, cursor will be move to next field, how can keep cursor on validation field?
function validation(id) {
var obj = document.getElementById(id);
obj.value = obj.value.toUpperCase();
if(value == "") {
obj.focus();
obj.select();
}
}
You can add an event on 'blur'. There after check for the keyCode. For tab key it is 0. Using an setTimeout since the current element will loss focus as soon as the is a onblur event. Therefore providing a sufficient time gap before focusing back on the element
var obj = document.getElementById('inputField');
obj.addEventListener('blur', function(event) {
if (event.which === 0 && event.target.value == '') {
setTimeout(function(){
event.target.focus();
},1000)
}
})
<input id='inputField' onchange='validation(this.id)'>
Adding the validation with button instead onchange event in input box .And if(value == "") value is a undefined so change the if condition with !Obj.value.trim() its catch the false condition .trim() used for remove unwanted space
Updated
use with blur
event instead of onchange .Its only allow to next input only present input was filled.
function validation(obj) {
obj.value = obj.value.toUpperCase();
if(!obj.value.trim()) {
obj.focus();
//obj.select();
}
}
<input id="input" type="text" onblur="validation(this,event)">
<input id="input" type="text" onblur="validation(this,event)">

jquery mobile function on.change works only sometimes

I have this code in jsfiddle, this code is supposed to check for invalid numerical values like -12-12. So the bug arises if I type an invalid numerical value (eg. -12-11) it removes the input (which is the expected behavior) and the weird part is that the second time it doesn't call the document.on change function.
The steps to reproduce the problem are as follows:
Type 12 for example.
Click somewhere else like the other textbox and that number will be
converted to decimal (12.00)
Type and incorrect number like -12-12 and click somewhere else and
the textbox will get cleared out (which is the expected behaviour).
The second time you type that number in the textbox it doesn't change
the value or clear the textbox.
This is something that I don't understand, by trying to debug the code the second time you insert a wrong number that function doesn't get called so I was wondering why.
Any help is appreciated.
My javascript code:
$(document).on('change', 'input[type="number"]', function(event) {
var target = $(event.target);
var max = target.attr('max') - 0;
var min = target.attr('min') - 0;
var step = target.attr('step');
var val = parseFloat(target.val());
if(typeof max !== 'undefined' && val > max) {
target.val(max);
}
else if(typeof min !== 'undefined' && val < min) {
target.val(min);
}
else if(typeof step !== 'undefined') {
if(step < 1) {
target.val(parseFloat(target.val()).toFixed(step.split('.')[1].length));
}
else {
debugger;
}
}
else if(val + '' != target.val()) {
target.val(val);
}
});
I see your issue, and able to solve it. I suggest you to use blur event instead of change event of textbox. This will work like a charm.
Here is the code :
$(document).on('blur', 'input[type="number"]', function(event) {
var target = $(event.target);
var max = target.attr('max') - 0;
var min = target.attr('min') - 0;
var step = target.attr('step');
var val = parseFloat(target.val());
if(typeof max !== 'undefined' && val > max) {
target.val(max);
}
else if(typeof min !== 'undefined' && val < min) {
target.val(min);
}
else if(typeof step !== 'undefined') {
if(step < 1) {
target.val(parseFloat(target.val()).toFixed(step.split('.')[1].length));
}
else {
debugger;
}
}
else if(val + '' != target.val()) {
target.val(val);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="transaction_amount">Amount</label>
<input type="number" data-mini="true" step="0.01" name="amount" min="0.01" max="1000000" id="transaction_amount" value="">
<label for="transaction_external_identifier" id="payment-description-label">Check #</label>
<input type="text" name="external_identifier" id="transaction_external_identifier" value="" data-mini="true">
When an invalid number is entered into the number type input, the browser regards that as blank (because it's invalid and it won't bother holding that value, so returns false when asked about validity. According to the Mozilla Developer Network). So if you type -12-12 again, the change event doesn't fire and hence it doesn't clear out because the underlying value is still blank. You'll see this if you first start with entering -12-12 into the blank input - it also won't work.
Your best bet is to change the onchange to onblur as it will be far more consistent since it doesn't look at the value.

Prevent user from typing in input at max value

I'd like the user to be blocked from typing more if the value is over 100. So far I have the following from reading different posts:
$('.equipCatValidation').keyup(function(e){
if ($(this).val() > 100) {
e.preventDefault();
}
});
To confirm I want the value not the string length, and it can't be above 100.
However this is not preventing further input in the field. What am I missing.
Checking keyup is too late, the event of adding the character has already happened. You need to use keydown. But you also want to make sure the value isn't > 100 so you do need to also use keyup to allow js to check the value then too.
You also have to allow people to delete the value, otherwise, once it's > 100 nothing can be changed.
<input class="equipCatValidation" type="number" />
When using input type="number", change also needs to be on the event list.
$('.equipCatValidation').on('keydown keyup change', function(e){
if ($(this).val() > 100
&& e.keyCode !== 46 // keycode for delete
&& e.keyCode !== 8 // keycode for backspace
) {
e.preventDefault();
$(this).val(100);
}
});
http://jsfiddle.net/c8Lsvzdk/
Basically keypress events are fired before accepting the current value. So when you press on any key, keypress event is subscribed but you don't get the updated value/result for the recently pressed key. So, to get the last pressed key we can use the fromCharCode method and concat it with the value we got from the textbox. That's it,
HTML :
<input id="inputBox" type="text" />
jQuery :
$("#inputBox").on("keypress", function(e){
var currentValue = String.fromCharCode(e.which);
var finalValue = $(this).val() + currentValue;
if(finalValue > 100){
e.preventDefault();
}
});
jsFiddle
Maybe keydown instead of keyup?
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(function() {
$('.equipCatValidation').keydown(function(e){
if ($(this).val() > 100) {
e.preventDefault();
}
});
})
</script>
</head>
<body>
<input type="text" class="equipCatValidation">
</body>
</html>
EDIT: There is a valid comment here - Prevent user from typing in input at max value - to circumvent that you should probably store the previous value and restore it when necessary.
It is bad UI to disable the input if a user inputs a bad value. I'm assuming you simply want to put a max value that the user cannot go over. If so, you can either clamp the value, or use the max attribute in your markup:
<form>
<input type='number' max='100'>
</form>
If you input an invalid value, the input will turn red, and you cannot submit the form.
<input class="equipCatValidation" />
var maxValue = 100;
jquery
$('.equipCatValidation').on('keypress', function(e){
/* preventing set value when it doesn't pass conditions*/
e.preventDefault();
var input = $(this);
var value = Number(input.val());
var key = Number(e.key);
if (Number.isInteger(key)) {
value = Number("" + value + key);
if (value > maxValue) {
return false;
}
/* if value < maxValue => set new input value
in this way we don't allow input multi 0 */
$element.val(value);
}
});
vanilla js
document.querySelector(".equipCatValidation")
.addEventListener("keypress", function(e) {
e.preventDefault();
var input = e.target;
var value = Number(input.value);
var key = Number(e.key);
if (Number.isInteger(key)) {
value = Number("" + value + key);
if (value > maxValue) {
return false;
}
input.value = value;
}
});
example
addition to the this answer
$('.equipCatValidation').on('keypress', function(e){
var $element = $(this);
var value = Number($element.val());
var key = Number(e.key);
if (Number.isInteger(key)) {
value = Number("" + value + key);
}
if (value > 100) {
return false;
}
});
Here's a solution for those using modern vanilla Javascript:
Just snap the value back down to the max when the user focuses away from the input.
You would set the input to a number type and the max value
<input type="number" max="100">
and then add a function to the onblur method of the element
document.querySelector('input[max]').onblur = function (event) {
// If the value is less than the max then stop
if (Number(event.target.value) < event.target.max) return
// Snap the value to the max
event.target.value = event.target.max
}
You can also use oninput instead of onblur but that may cause the user to have to fight the input in certain situations.
Example

recounting var when i delete characters

I have a script that remove "disabled" attr of my button when my 2 vars has 3 and 5 characters respectively.
But when I deleted my characters it doesnt count back, and add again the "disabled" attr to my button.
I dont know how to do it. Any suggestions ?
FIDDLE: http://jsfiddle.net/CCwKp/
HTML
<form action="" method="" class="login">
<ul class="userLogin">
<li>
<input type="text" placeholder="E-mail" class="user" />
</li>
<li>
<input type="password" placeholder="Senha" class="pass" />
</li>
</ul>
<button disabled />test</button>
</form>
JS
$(function () {
var user = 0;
var pass = 0;
function userPassAlert() {
if (user >= 3 && pass >=5) {
$('button').removeClass('disabled').addClass('available').removeAttr("disabled");
} else {
$('button').removeClass('available').addClass('disabled').attr("disabled");
}
};
$(".user").on('focus keypress', function() {
user++;
console.log(user);
userPassAlert();
});
$(".pass").on('focus keypress', function() {
pass++;
console.log(pass);
userPassAlert()
});
$('button').on('click', function (e) {
e.preventDefault();
if (user >= 3 && pass >=5) {
alert("done");
}
else {
return false;
}
});
});
Three things:
To add the "disabled" attribute back to the button, it has to be added as such:
$(".this").attr("disabled","disabled");
The counter is always adding to the user/pass when there is a mouse click or keypress so it will always go up and never down. If we change this to check the length of the value in the input when there is a mouse or key action, it will verify the actual length existing in the input field. You can do this by using:
user=$(".user").val().length;
Keyup is better to handle backspace than keypress. Replacing this in your "on" functions will provide a more accurate result.
JS Fiddle Here
You increment the user and pass on every keypress, even if you remove a character. I
would instead check the length of the values in the fields in your method userPassAlert():
function userPassAlert() {
if ($('.user').val().length >= 3 && $('.pass').val().length >=5) {
$('button').removeClass('disabled').addClass('available').prop("disabled", false);
} else {
$('button').removeClass('available').addClass('disabled').prop("disabled", true);
}
};

Categories

Resources