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
Related
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"/>
Using jquery, how to auto subtracting amount from input after typing it without button
Ex. When I type a number in an input , I want to subtract it -5 after I leave it automaticaly without submit button , 200 will be 195 .
Is it posible?
Ok here's a quick way to do this in jquery. Try the code below. Add a number and tab off the input or click out of it and the value will change.
$('input').on('blur', function() {
var num = $(this).val() - 5;
$(this).val(num);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
EDIT: In case you are looking for a pure JavaScript alternative (without jQuery):
You can attach this process to an input event such as onkeyup or onfocusout:
function update() {
amount = document.getElementById("amount");
amount.value = parseInt(amount.value) - 5;
}
<input type="text" id="amount" onfocusout="update()">
JavaSript solution.
This will work for you.
document.getElementById("input").onblur = substract;
function substract() {
let firstValue = event.currentTarget.value;
let finalValue = Number(firstValue) - 5;
document.getElementById("input").value = finalValue;
}
To do this you need need to create a function and attach the input Element to the function.
Creating a function to reduce input element on change by 5.
var myfunction = function(){
var value = parseInt(this.value);
//check if input is of type int and less than five to avoid negative numbers.
if( !value || value < 5 ){
return false;
}
this.value = value - 5;
};
//ataching function to the element
var element = document.getElementById('my_input');
element.addEventListener( 'change', myfunction, false );
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)">
So I was trying replace the key press "K" with "Z" in an input field.
I was successfully able to do it. But there is a slight delay which makes the user see that the "K" being changed to "Z".
This is my code:
function prinner (event)
{
document.getElementById("txx").innerHTML= event.key; //Displays key pressed on screen by changing text element.
if(event.keyCode == 32){
// User has pressed space
document.getElementById("txx").innerHTML= "Space";
}
if (event.key=="k") // Trying to replace this with z.
{
var curval = $("#namaye").val(); //namaye is the ID of the input field.
var nval = curval.slice(0,(curval.length-1))+"z";
$("#namaye").val(nval);
}
}
$("#namaye").keyup(prinner);
Does anyone know a better way to achieve this without the delay?
Use keydown instead of keyup and cancel the event so the key stroke doesn't actually get printed:
function prinner (event) {
// Displays key pressed on screen by changing text element.
document.getElementById("txx").innerHTML= event.key;
if(event.keyCode == 32){
// User has pressed space
document.getElementById("txx").innerHTML= "Space";
}
// Trying to replace this with z.
if (event.key=="k") {
var curval = $("#namaye").val(); //namaye is the ID of the input field.
var nval = curval +"z";
$("#namaye").val(nval);
// Cancel the event
event.preventDefault();
event.stopPropagation();
}
}
$("#namaye").keydown(prinner);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="namaye">
<p id="txx"></p>
Use keydown event, and cancel the default behaviour when k is pressed. Also, use selectionStart and selectionEnd properties to replace the characters that were selected at the moment the key was pressed, and to put the cursor at the right position, just after the inserted z:
function prinner (event) {
$("#txx").text(event.keyCode == 32 ? "Space" : event.key);
if (event.key=="k") {
var s = $(this).val();
var i = this.selectionStart;
s = s.substr(0, i) + "z" + s.substr(this.selectionEnd);
$(this).val(s);
this.selectionStart = this.selectionEnd = i + 1;
return false;
}
}
$("#namaye").keydown(prinner);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="namaye">
<div id="txx"></div>
Since you use jQuery, use $("#....") instead of the more verbose document.getElementById("...."). Also, in the event handler, this will be input element, so use that reference.
Try using keydown? It happens before the input is actually modified: in fact, if you return false (or e.preventDefault()) inside a keydown listener, it will actually cancel the keystroke, which I think is what you want. Then you manually add your new key. Something like (untested and skipping some details for clarity):
function prinner (event)
{
if (event.key=="k")
{
event.preventDefault() // makes sure the 'k' key never goes to the input
$("#namaye").val( $("#namaye").val() + 'z' );
}
}
$("#namaye").keyup(prinner);
You have to add an event.preventDefault() inside your if clause to stop the event propagation and then you can insert your "z" key.
I'm using an ID scanner that acts as a keyboard input and I want an input field to listen for the value and substring (or slice) out unnecessary, extra values.
Currently, the ID scanner formats numbers like this: ;708089113=0184?
I want to grab only the 708089113. I want to remove the semi-colon and everything after the 3.
I'm just not sure how to do this automatically. The stripped value should appear in the field before submitting.
Javascript:
var suid = document.getElementById("SUID").value;
var stripSUID = suid.substring(1,10);
document.getElementById("SUID").value = stripSUID;
HTML:
<input name="SUID" id="SUID" type="text" value="">
JSFiddle Link
You can use jQuery for this.
HTML:
<input name="suid" id="suid" type="text" value="">
JavaScript:
$(function() {
$('#suid').change(function() {
var suid = $(this).val();
var stripSUID = suid.split('=');
var stringLength = stripSUID[0].length;
var returnValue = stripSUID[0].substr(1, stringLength);
$(this).val(returnValue);
});
});
jsFiddle update: http://jsfiddle.net/jhjr288o/4/
So you're asking how to listen for a change to the <input>?
var elm = document.getElementById('SUID');
elm.addEventListener('change', function (e) {
var s = this.value, i = s.indexOf('=');
if (i !== -1) {
s = s.slice(1, i);
this.value = s;
}
});
DEMO
The change event fires when the element loses focus
The input event fires every time oldvalue !== newvalue (i.e. for every char typed)
Also note, this code must be run after the Element exists, i.e. wait for the Window's load event