How to restrict Textbox value with the max value on key events? - javascript

I have a text box i want to restrict that value for max value using key events
I try with the below code and its work fine
function validateRange(ele) {
if(ele.val() < 0 || ele.val() > 100){
console.log('false');
}else{
console.log('true');
}
}
$('.digit-validation').keyup(function(event){
validateRange($(this));
});
HTML:
<form:input type="text" path="depth" cssClass="number inplace-textbox digit-validation" data-min="0" size="10" />
I would like if(ele.val() < 0 || ele.val() > 100) is stop keypress.
Update: I am trying to do range of values validation.

I'd suggest that you try and use the HTML5 input type of number, with min and max attributes:
<input type="number" min="0" max="100" />
JS Fiddle demo.
This allows the user to enter a number directly (using the keyboard, or copy/paste), and allows for control of the increments using the step attribute (step="2", for example, will allow increments, or decrements, of 2 on every click of the spinner arrows).
If, however, you must use a non-number input:
Number.prototype.between = function (a, b, inclusive) {
var min = Math.min.apply(Math, [a,b]),
max = Math.max.apply(Math, [a,b]);
return inclusive ? this >= min && this <= max : this > min && this < max;
};
$('.digit-validation').keydown(function(event){
var v = parseFloat(this.value + String.fromCharCode(event.which));
return parseFloat(v).between(0,100,true);
});
JS Fiddle demo.

Why do you not use maxlength HTML attribute ?
<input type="text" maxlength="100" />
There is no need to use JS to achieve this.

For your validation, you need 2 things :
check if the user enters a number
check if the user enters something between 0 and 100
For the 1st one, since you use jQuery, you can use $.isNumeric().
For the 2nd one, you need to parse the value as integer thanks to parseInt().
That would give you :
http://jsfiddle.net/tLwYX/
function validateRange(ele) {
var val = ele.val();
if(!$.isNumeric(val) || parseInt(val,10) < 0 || parseInt(val,10) > 100){
$('#result').html('false');
}else{
$('#result').html('true');
}
}
$('.digit-validation').keyup(function(event){
validateRange($(this));
});

Related

How to allow only digits to be entered into an input[type="number"] field?

I have an input field in which the user should only be able to enter digits [0-9].
document.getElementById("integer").addEventListener('input', restrictToInteger);
function restrictToInteger() {
this.value = this.value.replace(/[^\d]/g, '');
}
<input type="number" id="integer" />
jsFiddle Demo
The problem is this: When I enter a number (eg. 1234) and then press dot (.), + or - the content of the input field is automatically deleted by the browser (value is set to "" = empty string). But why? Changing the type from number to text seems to fix the problem. But then I lose the up/down arrow functionality of the input field. Any ideas?
HTML 4 has an event called onkeypress. With that attribute we can do this without using additional JS:
<input type="number" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57">
Here digits from 0 to 9 are allowed using the event.charCode from 48 to 57.
I think the reason that the browser clean the input value it is because a string with two dots it is not a number.
Some corrections about your code:
You need to change your expression regular if you want to accept number with decimal part. Now, you are only express that you want to accept digits [0-9] and no more chars.
To accomplish want you want, you need to change /[^\d]/g to /[^\d.]/g.
document.getElementById("integer").addEventListener('input', restrictToInteger);
function restrictToInteger()
{
this.value = this.value.replace(/[^\d.]/g, '');
}
<input type="number" id="integer" />
HOWEVER: If you define your input as number type, the regular expression is not needed. So, you just need to define the input like this and should your to your case:
<input type="number" id="integer" />
[THE SOLUTION]
To fully meet your needs, I came with a solution that catch the keydown event of the input and check if there is any '.' on the input. If yes, I prevent the char to go to the input.
document.getElementById("integer").addEventListener('keydown', restrictToInteger);
var lastCodeWasDot = false;
function restrictToInteger(e)
{
var inputValue = document.getElementById("integer").value;
var isDot = false;
var isDot = (e.keyCode && e.keyCode == 110) || (e.charCode && e.charCode == 190);
console.log(e.keyCode);
if(isDot && (inputValue.indexOf(".") > -1 || inputValue == "" || lastCodeWasDot)) {
e.preventDefault();
}
lastCodeWasDot = isDot;
}
<input type="number" id="integer" />
Explaning the solution:
The line of code var isDot = (e.keyCode && e.keyCode == 110) || (e.charCode && e.keyCode == 190) || false; is needed because cross browser compatibility.
I don't now why but if you try to get the value from an input number type in the firefox, and if the value finishes with a dot, the value that you will get will be without the last dot of the input. To fix that, I needed to add the variable lastCodeWasDot to fix this issue.
NOTE: The number input can accept floating point numbers, including negative symbols and the e or E character (check out this post)
Based on the answers of Alexandru-Ionut Mihai and natchiketa I created the following solution:
document.getElementById("integer").addEventListener("input", allowOnlyDigits);
function allowOnlyDigits() {
if (this.validity.valid) {
this.setAttribute('current-value', this.value.replace(/[^\d]/g, ""));
}
this.value = this.getAttribute('current-value');
}
<input type="number" id="integer" />
On input the value is checked for validity. If it is valid, all non-digits are removed and the value is stored in a custom attribute of the element. If the value is not valid, the previous value is restored.
Notes:
The RegEx-replace is required only for Internet Explorer as it allows you to enter , or . at the end of a number.
Tested in IE, Edge, Chrome and Firefox
Chrome still allows you to enter a + before and one , after the number.
I found one issue: If you initialize the field with a value, the value is lost when you first hit an invalid char on the keyboard.
Another issue: You can't enter a negative number.
The only problem was your input type. Change it to text and it should work !
function validate(e) {
var charCode = e.keyCode? e.keyCode : e.charCode
if (!(charCode >= 48 && charCode <= 57)) {
if(!(charCode>=37 && charCode<=40))
if(charCode!=8 && charCode!=46)
return false;
}
}
<input type="number" id="integer" pattern="[0-9]"
onkeydown="return validate(event)"/>
You can achieve your requirement by copying the old value of input and using setAttribute and getAttribute methods in order to store the values.
function myFunction(input){
input.setAttribute('current-value',"");
input.oninput=function(){
let currentValue=input.getAttribute('current-value');
if(input.value!='' || (currentValue>=1 && currentValue<=9))
input.setAttribute('current-value',input.value);
input.value=input.getAttribute('current-value');
}
}
<input type="number" oninput="myFunction(this)"/>
<input type="number" oninput="myFunction(this)"/>
<input type="number" oninput="myFunction(this)"/>
<input type="number" oninput="myFunction(this)"/>
<input type="number" oninput="myFunction(this)"/>
When you call oninput, the <input> element first calls its internal methods to handle the value. This prevents your function from seeing any actual erroneous characters, namely e+-. - all used by JavaScript to format numbers.
You can see this by adding console.log calls before and after changing this.value.
console.log(this.value);
this.value=this.value.replace(/[^\d]/g, '');
console.log(this.value);
There is never any difference!
If you try, for example:
console.log(this.value);
this.value+=1; // or *=2 for numerical fun
console.log(this.value);
you can see a difference.
So your function is hastening the normal internal calls <input type='number'/> would normally make when handling illegal input.
Can't quite see why the field is left blank and not 1 though.
I would switch to a cancelable event like keydown.
That way you can prevent the character from being typed in the first place:
var cancelEvent = function (e) {
e.preventDefault();
return false;
},
restrictToInteger = function restrictToInteger(e) {
var acceptableInput = /[0-9]/g,
clipboardKeys = /[zxcv]/ig,
field = e.key || e.char,
isClipboardOperation = (clipboardKeys.test(field) && e.ctrlKey),
inputIsAcceptable = field ? (
acceptableInput.test(field)
|| field.length > 1
|| isClipboardOperation
) : true;
if (!inputIsAcceptable) {
cancelEvent(e);
}
},
ensureIntegerValueOnPaste = function ensureIntegerValueOnPaste(e) {
var data = e.clipboardData || e.dataTransfer,
text = data.getData('text'),
int = parseInt(this.value + text, 10);
if (isNaN(int)) {
cancelEvent(e);
} else {
window.setTimeout(function () {
e.target.value = int;
}, 0);
}
},
input = document.getElementById("integer");
input.addEventListener('keydown', restrictToInteger);
input.addEventListener('drop', ensureIntegerValueOnPaste);
input.addEventListener('paste', ensureIntegerValueOnPaste);
<input type="number" id="integer" />
Updated fiddle: https://jsfiddle.net/838pa8hv/2/
Disclaimers:
Only tested in Chrome.
The test for field.length > 1 is to catch non-numeric keys that are valid as the up/down arrows have a value of ArrowUp and ArrowDown respectively. This also allows for keys like Shift (or Home, Backspace, Delete, etc.) to be pressed as well.
Edit:
To handle pastes (and drops), you can do the same thing in those respective events. Updated fiddle and code snippet above.
Edit:
If the expected usability is to be able to paste/drop partial numbers into the field and to not allow negative integers, then you can just change how int is defined in the ensureIntegerValueOnPaste function. Updated fiddle and code snippet above.
You don't need regular expression, you can use parseFloat() function. Your input type remains unchanged, there are still "arrows" to increase/decrease number and also it makes sure that your input will not start with zero.
document.getElementById("integer").addEventListener('input', restrictToInteger);
function restrictToInteger() {
this.value = parseFloat(this.value);
}
<input type="number" id="integer" />
You have to check if the value is not a number and then stop user.
document.getElementById("integer").addEventListener('input', restrictToInteger);
function restrictToInteger(e)
{
if(isNaN(e.data)){
alert("only numbers allowed");
}
}
<input type="number" id="integer" />

check if input is between two int or float then display or not display content

In javascript I need to check whiwh value user enter in an html input like this:
<input type="text" id="volume" class="form-control" name="voilume"></input>
<div id"button"></div>
Ineed to know if the input is between 0,5 and 8 (so I have int and float as you can understand).
So the value has to be >= 0,5 and <= 8
If value input if between 0,5 and 8 I have to display a button, else nothing to do. But I need to prevent if user change the value many times.
So if he enters 3 display a button in div id=button", if it changes for another value like 2 for example keep displaying the button, but if he changes value input for 100 I need to remove the button in div id="button".
for now I tried something like this in order to test if it works:
var input= $('#volume').val();
if (input >= 0.5 && input <= 8) {
$('#button').html('ok');
} else {
$('#button').empty();
}
But it does not work.
You can exploit the CSS Constraint Validation here a little bit. It seems to me like a X/Y Problem. Actually, we could set our min, max and step values for this <input> element and then let the browser do the validation:
<input type="number" min="0.5" max="8" step="0.1" required id="volume" class="form-control" name="voilume">
Alongside this, we can make usage of the pseudo css selectors :valid and :invalid like so:
input:valid~div#button {
display: block;
}
input:invalid~div#button {
display: none;
}
This would have the effect, that if we enter a valid value in our input control, the button will be displayed. If not, the button disappears. Magic!
Example: https://jsfiddle.net/4q1fjqwp/
.val() of an input field is a string, you have to convert it to a number in order to be able to compare it to numbers by >=, <=. You also had a typo: id"button"
function go() {
var input=parseFloat($('#volume').val(), 10);
if (input >= 0.5 && input <= 8) {
$('#button').html('ok');
} else {
$('#button').empty();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="volume" class="form-control" name="voilume"/>
<div id="button"></div>
<button onclick="go()">run</button>
The problem may happen when input contain comma ,
so "0,5" >= 0.5 will return false and parseFloat("0,5") will return 0.
You need replace , with .
Something like below will work.
<input type="text" id="myTextField" onblur="change()"/>
<input type="submit" id="byBtn" value="" />
JavaScript
function change() {
var myTextbox = document.getElementById('myTextField').value;
var button = document.getElementById('byBtn');
if (parseFloat(myTextbox) >= 0.5 && parseFloat(myTextbox) <= 8) {
button.value = "OK";
} else {
button.value = "";
}
}
you need to parse string value to integer. for that use parseInt().
it will parse string to integer.
replace this:
var input= $('#volume').val();
by
var inputval= parseInt($('#volume').val());

Prevent min > max values on input type=number

I have two input numbers (min and max). Is there a way to prevent user inserting values like min > max?
<input type="number" class="inputMin" placeholder="Min.">
<input type="number" class="inputMax" placeholder="Max.">
There are many different ways you can do this.
One option is whenever min is changed, if it is greater than max, change it to equal max, like this:
$('.inputMin').on('change', function() {
var max = parseFloat($('.inputMax').val());
var min = parseFloat($('.inputMin').val());
if (min > max) {
$('.inputMin').val(max);
}
});
or the opposite case when you change max:
$('.inputMax').on('change', function() {
var max = parseFloat($('.inputMax').val());
var min = parseFloat($('.inputMin').val());
if (min > max) {
$('.inputMin').val(max);
}
});
Another option is to display an error, either when the form is submitted, or dynamically as the user changes the input.
There are a number of javascript libraries that allow you to do dynamic validation very easily. Check out Angular.js, and how to use it for form validation.
Without JQuery, you can try this :
(and you have to change class to id)
var min = document.getElementById("inputMin");
var max = document.getElementById("inputMax");
function check() {
if (min.value > max.value) {
min.value = max.value;
}
};
min.addEventListener("input", check, false);
max.addEventListener("input", check, false);
You can try it there
You can use the parameters min and max like:
<form>
Quantity (between 1 and 5):
<input type="number" name="quantity" min="1" max="5">
</form>
Ref: http://www.w3schools.com/html/html_form_input_types.asp (Input Type: number)
Also you can use Javascript to check if the value is >= min_number and <= max_number, but both are client side scripts, which can be bypassen with editing the html part.
You also need a server-side check so you can be sure it's within the range.

if input field is not a number OR not empty replace with a number

I have an input field that I am monitoring for changes using an .on('input') function as this covers .change and .keyup.
There is no submit button yet I just want to change the behaviour of the input field depending on what is entered.
I will validate server side later and I'm using html5 type='number'.
I only want the field to be able to hold a number, or it can be empty. The user might want to empty the contents to type the number 15 for example.
However I don't want any other characters to be accepted - if they are entered, a prompt should show notifying the user of this and the field is defaulted back to it's starting value of 1.
HTML
<input type="number" class="input-field" placeholder="" value="1" min="1">
JS
$(document).ready(function ($) {
var num = $('input[type="number"]').val();
$('input[type="number"]').on('input', function () {
var num = $(this).val();
if (num < 1 || isNaN(num) || num !== '') {
alert(num + ' is not a number or is less than 1');
$(this).val(1);
}
});
});
I have tried with the above code and it doesn't allow for an empty field. I've also tried if (num < 1 || isNAN(num) || num.length != 0) {
do I need to use .replace() with a Regexr. I've been looking at a few questions on here like here but I'm not sure thats what I'm looking for considering I'm testing for an empty string.
JSFIDDLE
You can use the constraint validation API:
$('input[type="number"]').on('input', function () {
if (!this.validity.valid) {
alert(this.value + ' is not a number or is less than 1');
this.value = 1;
}
});
$('input[type="number"]').on('input', function () {
if (!this.validity.valid) {
alert(this.value + ' is not a number or is less than 1');
this.value = 1;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="number" class="input-field" placeholder="" value="1" min="1">
However, note that this behavior is obtrusive. If an user types the wrong key, you will annoy him with a modal dialog and will clear the number.
Consider doing nothing. HTML5 browsers won't send the form if the input is not valid.
The HTML5 answer is definitely more elegant.
But if you want to offer more support, this is usually the route I take when trying to verify numbers.
Note that I am using data-min attribute but if you want to switch you can always use $.attr() to grab your min="" attribute.
$(document).ready(function ($) {
$('input[type="number"]').on('change', function () {
var min = parseInt(this.dataset.min),
num = isNaN(parseInt(this.value)) ? 0 : parseInt(this.value),
clamped = Math.max(num, min);
if(num != clamped) {
alert(num + ' is less than 1');
this.value = clamped;
}
});
});
jsfiddle

Html textbox: how to restrict input values to only numbers less than 15

I am wanting to only have input values of 01,02,...,09,10,11,12,..,15 permissible in my text field. Please help the newbie with a sample code on how to achieve this. (not using HTML5 yet)
try:
<script type="text/javascript">
function validateForm()
{
var x=document.forms["myForm"]["YourTextBoxID"].value;
var y = parseInt( x , 10 )
var i=15;
if (y>i)
{
alert("Out of range");
return false;
}
}
</script>
A Sample, why not allow user to enter only numbers? Try this out
<HTML>
<HEAD>
<SCRIPT language=Javascript>
<!--
function isNumberKey(evt) ' Allow user to enter only numbers
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (((charCode > 47) && (charCode < 58 ) ) || (charCode == 8))
return true;
return false;
}
function isless() ' do not submit if greater than 15
{
var num = document.getElementById('num_txt').value
var y = parseInt( num , 10 )
if ( y > 15 )
return false;
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<FORM onsubmit="isless()" action="some.php">
<INPUT id="num_txt" onkeypress="return isNumberKey(event)" type="text" >
</FORM>
</BODY>
</HTML>
Well, since you tagged your question with "regex", the regex you want is something like this:
/^(0[\d]|1[1-5])$/
Or if you want to make the initial "0" optional:
/^(0?[\d]|1[1-5])$/
As far as how you use that, well, if you show the code you've got so far I can advise how to fit it in...
I think you can use comboBox.. some code to get started :
<select >
<option> 01 </option>
<option> 02 </option>
</select>
http://www.w3schools.com/tags/tag_select.asp
You have a couple of choices. Users who use a keyboard like to enter text manually so for them it is best to put a hint on the screen that the input should have a value from '01' to '15'. Let the user enter whatever they want and validate it when the form is submitted.
Another option is to use a select element with the values you want, or a sequence of radio buttons. It all depends on your users, the data you are collecting (e.g. dates, counts, ages, whatever).
So find out what your users would like, then implement it. Client side validation is all about making life better for the user, it is not a way of forcing them to do what you want—that's what server side validation is for. :-)
Here's a somewhat brittle, but complete solution for this:
In this case, you'd have a text input with an id of test:
<input type="text" id="test"/>
Here's your script:
var numbers = [48,49,50,51,52,53,54,55,56,57];
$("#test").bind("keyup",function(e){
var num = numbers.indexOf(e.which),
t = $(e.target),
v = t.val(),
len = v.length;
if(len > 2){
t.val(v.match(/(.+?).$/)[1]);
} else {
if(v[0] == 1){
if(v[1] && v[1] > 5){
t.val(15);
}
} else if(v[0] != 0) {
t.val("");
}
}
});
basically, I assign the key codes of all letters to corresponding indices of an array.
Then, on each key down, we figure out what key it is, and if it's in position 0, check if it's 0 or 1.
if it's in position 1, check if it's greater than 5 as long as the first number is 1.

Categories

Resources