I have a percentage textbox. I want to enter values 0 to 100. Not more than 100 or negative values.
FIDDLE
Please check this fiddle. Here, it is allowing only 2 digit values like 99 only and after 99 it is allowing number of decimals(99..........9999) like this. Need to allow only one decimal point and I can enter 100 also.
Note :
Can Enter 0 to 100 and not negative and not more than 100.00
After decimal I want to enter only 2 digits like, 99.99 only.
Do not allow negative values.
Allow only one decimal point like(9.99 or 99.99). Not (9.......9..9...80099 or 99.......9......9).
<script>
function check(e,value){
//Check Charater
var unicode=e.charCode? e.charCode : e.keyCode;
if (value.indexOf(".") != -1)if( unicode == 46 )return false;
if (unicode!=8)if((unicode<48||unicode>57)&&unicode!=46)return false;
}
function checkLength(){
var fieldVal = document.getElementById('txtF').value;
//Suppose u want 3 number of character
if(fieldVal < 100){
return true;
}
else
{
var str = document.getElementById('txtF').value;
str = str.substring(0, str.length - 1);
document.getElementById('txtF').value = str;
}
}
</script>
<input id="txtF" type="number" onKeyPress="return check(event,value)" onInput="checkLength()" />
<p id="s"></p>
Please help me how can I do this using jQuery or JavaScript.
Updated fiddle. This solves it for now, but the use of step=0.01 may not be what you want. Setting the step to 0.01 allows us to check the validity state of the input.
The validitiy state is not updated an a "before" event so on an "after" event we rollback the input.
<input id="txtF" type="number" onInput="return check(event,value)" min="0" max="100" step="0.01" />
check = function (e,value){
if (!e.target.validity.valid) {
e.target.value = value.substring(0,value.length - 1);
return false;
}
var idx = value.indexOf('.');
if (idx >= 0 && value.length - idx > 3) {
e.target.value = value.substring(0,value.length - 1);
return false;
}
return true;
}
<script>
var point=false;
var count=0;
function check(e,value){
//Check Charater
debugger;
if(count==3)return false;
var unicode=e.charCode? e.charCode : e.keyCode;
if( unicode == 46 && point==true)
return false;
if( unicode == 46 && point==false)
{
point=true;
}
if (unicode!=8)if((unicode<48||unicode>57)&&unicode!=46)return false;
if(point==true)count++;
}
function checkLength(){
var fieldVal = document.getElementById('txtF').value;
//Suppose u want 3 number of character
if(fieldVal <= 100){
return true;
}
else
{
var str = document.getElementById('txtF').value;
str = str.substring(0, str.length - 1);
document.getElementById('txtF').value = str;
}
}
</script>
<input id="txtF" type="number" onKeyPress="return check(event,value)" onInput="checkLength()" />
<p id="s"></p>
http://jsfiddle.net/ySt7S/130/
Related
I have a number field to which I need to apply certain conditions with pure JS or jQuery:
Max 30
Min -30
Only 2 digits after the point, example 2.25
So possible values are like this (2.00 / 2.25 / 2.50/ 2.75 / 3.00...)
I managed to do so unless for the last condition that should accept only values .00 or .25 or .50 or .75
Here is my code:
var t_myField = false;
var myField_min = -30;
var myField_max = 30;
$('#myField').focus(function ()
{
var $this = $(this)
t_myField = setInterval(
function ()
{
if (($this.val() < myField_min || $this.val() > myField_max) && $this.val().length != 0)
{
if ($this.val() < myField_min)
{
$this.val(myField_min)
}
if ($this.val() > myField_max)
{
$this.val(myField_max)
}
}
}, 50)
});
$('#myField').on("keyup", function (e)
{
// Replacer , by .
$(this).val($(this).val().replace(/,/g, '.'));
// Allow only float numeric values (positif & negatif)
var self = $(this);
self.val(self.val().replace(/[^0-9\.-]/g, ''));
if (e.which != 46 && e.which != 45 && e.which != 46 && !(e.which >= 48 && e.which <= 57))
{
e.preventDefault();
}
// Allow max 2 digits after decimals for certain fields
match = (/(\d{0,2})[^.]*((?:\.\d{0,2})?)/g).exec(this.value.replace(/[^\d.]/g, ''));
this.value = match[1] + match[2];
});
<input type="text" name="myField" id="myField" class="myField">
JSFIDDLE => https://jsfiddle.net/Cartha/vq65Lypj/5/
[EDIT]
Control should be on keyup. This is why I can't use html5 attributes like min/max/step...
You can make use of % operator like x % 0.25 == 0 ? true : false
let myField = document.getElementById('myField');
myField.addEventListener('keypress', onlyNumbers,{passive: false});
myField.addEventListener('change', checkInput);
function onlyNumbers(e) {
if (!isNumberKey(e)) {
e.preventDefault();
}
}
function isNumberKey(e) {
return (e.which <= 31 || (e.which >= 48 && e.which <= 57) || e.which === 45 || e.which === 46);
}
function checkInput(e) {
let x = parseFloat(e.target.value);
if (!isNaN(x)) {
if (x > 30) {
x = 30;
} else if (x < -30) {
x = -30;
} else if (x % 0.25 !== 0) {
x = Math.round(x / 0.25) * 0.25;
}
e.target.value = x.toFixed(2);
}
}
This will allow only numbers with 0.25 steps.
Digit-only algorithm has been improved to completely prevent other type of input to be displayed (your code shows the forbidden input and then erases it).
This is the basic idea, a lot of other improvements can be made. For example, to always show two decimals (EX. 2.00 instead of 2), make an animation, etc. Currently, the check is set to happen after focus ends.
NOTE: Little extra improvements made in last edit.
JS Fiddle (I don't know how to embed it to the answer)
I would recommend creating a web component here. I'll show you the basic setup for a customized built-in with a component that already works and does not involve fumbling with $(document).ready() or DOMContentLoaded:
class DecimalInput extends HTMLInputElement {
constructor() {
super();
this.addEventListener('input', (e) => {
const val = parseFloat(this.value),
min = parseFloat(this.min),
max = parseFloat(this.max),
step = parseFloat(this.step);
if (val%step !== 0) {
this.value = Math.round(val/step) * step
}
if (val > max) {
this.value = max
}
if (val < min) {
this.value = min
}
this.value = Number(this.value).toFixed(2, 10);
})
}
}
customElements.define('decimal-input', DecimalInput, { extends: 'input' })
<input type="number" is="decimal-input" min="-30" max="30" step="0.25" value="0" />
This component is already quite close to your requirements. Use it to do our own refinements based on this.
I need a function that will add the colon (:) after you type two numbers in input and I found this solution here on StackOverflow as well which is what I need. It add colon after typed second number and won't let u add more than 4 numbers.
However, there is an issue that I can't understand and solve. I need to be able to delete all numbers, but it won't let me. I can delete only last two, and you can't delete colon.
Here is the current code:
var time = document.getElementsByClassName('time');
for (var i = 0; i < time.length; i++) {
time[i].addEventListener('keyup', function (e) {
var reg = /[0-9]/;
if (this.value.length == 2 && reg.test(this.value)) this.value = this.value + ":"; //Add colon if string length > 2 and string is a number
if (this.value.length > 5) this.value = this.value.substr(0, this.value.length - 1); //Delete the last digit if string length > 5
});
};
https://jsfiddle.net/bubxm7pe/
You can add condition for backspace with e.keyCode
It works here
if (e.keyCode != 8)
{
var reg = /[0-9]/;
if (this.value.length == 2 && reg.test(this.value)) this.value = this.value + ":"; //Add colon if string length > 2 and string is a number
if (this.value.length > 5) this.value = this.value.substr(0, this.value.length - 1); //Delete the last digit if string length > 5
}
Update: You can also restrict user with digits like following. It also works here
//called when key is pressed in textbox
$(".time").keypress(function (e) {
//if the letter is not digit then don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
else
{
var reg = /[0-9]/;
if (this.value.length == 2 && reg.test(this.value)) this.value = this.value + ":"; //Add colon if string length > 2 and string is a number
if (this.value.length > 4) this.value = this.value.substr(0, this.value.length - 1); //Delete the last digit if string length > 5
}
});
Rather than check for delete or backspace you could check if the key pressed is a number:
if (keycode >= 48 && keycode <= 57) {
if (this.value.length == 2 && reg.test(this.value)) this.value = this.value + ":"; //Add colon if string length > 2 and string is a number
if (this.value.length > 5) this.value = this.value.substr(0, this.value.length - 1); //Delete the last digit if string length > 5
}
https://jsfiddle.net/6jbaayqd/
As you are already inclined to use regex, then why not use it for formatting the time in the input field - see demo below:
document.getElementsByClassName('time')[0].addEventListener('keyup', function(e) {
this.value = this.value
.replace(/[^\d]/g, '') // allow only digits
.replace(/^([\d]{4})\d+$/g, '$1') // restrict to 4 chars
.replace(/\B(?=(\d{2})+(?!\d{1}))/g, ":"); // place the colon
});
<input class="time" />
Today i have problem in delimiting number for negative and positive number. For example, i have a textbox to insert my number and the result after write the number. Suddenly the number is separated with comma delimiter like this either the number is positive or negative
eg : 1000 -> 1,000
-1000 -> -1,000
-1000.12 -> -1,000.12
-0.00001 -> -0.00001
How to achieve this using javascript, what i know is using onkeypress and onkeyup. Thank you very much :)
This is not the best solution, but you can implement this according to your need.
var msg = document.getElementById('myInputBox'),
numberPattern = /^[0-9]+$/;
msg.addEventListener('keyup', function(e) {
msg.value = getFormattedData(msg.value);
});
function checkNumeric(str) {
return str.replace(/\,/g, '');
}
Number.prototype.format = function() {
return this.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
};
function getFormattedData(num) {
var i = checkNumeric(num),
isNegative = checkNumeric(num) < 0,
val;
if (num.indexOf('.') > -1) {
return num;
}
else if (num[num.length - 1] === ',') {
return num;
}
else if(i.length < 3) {
return i;
}else {
val = Number(i.replace(/[^\d]+/g, ''));
}
return (isNegative ? '-' : '') + val.format();
}
<input type="text" id='myInputBox' value="" />
I am trying to create a javascript function which is called on keypress event on a input which does the following:
Input should be a valid decimal with format (5,2) => (XXXXX.YY) which are variable to the function. Input is restricted if user adds any value which does not conform to the format above.
If existing input starts with . append 0 to the starting automatically
HTML
<input type="text" onkeypress="return checkDecimal(event, this, 5, 2);" id="price2" value="27.15">
Javascript
function checkDecimal(evt, item, lenBeforeDecimal, lenAfterDecimal) {
var charCode = evt.which;
var trimmed = $(item).val().replace(/\b^0+/g, "");
if(checkStartsWith(trimmed, '.') == true){
trimmed = '0' + trimmed;
}
//Allow following keys
//8 = Backspace, 9 = Tab
if(charCode == 8 || charCode == 9){
return true;
}
//Only a single '.' is to be allowed
if(charCode == 46){
var dotOccurrences = (trimmed.match(/\./g) || []).length;
if(dotOccurrences != undefined && dotOccurrences == 1){
return false;
}else{
return true;
}
}
if (charCode > 31 && ((charCode < 48) || (charCode > 57))) {
return false;
}
if ($(item).val() != trimmed){
$(item).val(trimmed);}
//Check the start and end length
if(trimmed.indexOf('.') == -1){
if(trimmed.length >= parseInt(lenBeforeDecimal)){
return false;
}
}else{
var inputArr = trimmed.split(".");
if(inputArr[0].length > parseInt(lenBeforeDecimal) || inputArr[1].length >= parseInt(lenAfterDecimal)){
return false;
}
}
return true;
}
function checkStartsWith(str, prefix){
return str.indexOf(prefix) === 0;
}
Issues
If user inputs 12345.9 and then moves the caret position after 5, user is able to add another digit before the decimal 123456.9 which should not be allowed.
If user inputs 1.9 and then remove 1 and add 5, 5 is added at the end and the entered value becomes 0.95 and not 5.9
JS Fiddle
Consider using a regular expression like:
/^(\d{0,5}\.\d{0,2}|\d{0,5}|\.\d{0,2})$/;
that allows everything up to and including your required format, but returns false if the number part is more than 5 digits or if the fraction is more than 2 digits, e.g.:
<input type="text" onkeyup="check(this.value)"><span id="er"></span>
<script>
function check(v) {
var re = /^(\d{0,5}\.\d{0,2}|\d{0,5}|\.\d{0,2})$/;
document.getElementById('er').innerHTML = re.test(v);
}
</script>
You'll need separate validation for the final value, e.g.
/^\d{5}\.\d{2}$/.test(value);
to make sure it's the required format.
I don't understand the requirement to add a leading zero to "." since the user must enter 5 leading digits anyway (unless I misunderstand the question).
I have this code:
<script type="text/javascript">
var maxLength=10;
function charLimit(el) {
if (el.value.length > maxLength) return false;
return true;
}
function characterCount(el) {
var charCount = document.getElementById('charCount');
if (el.value.length > maxLength) el.value = el.value.substring(0,maxLength);
if (charCount) charCount.innerHTML = maxLength - el.value.length;
return true;
}
</script>
together with this input field:
<input type="text" onKeyPress="return charLimit(this)" onKeyUp="return characterCount(this)" />
<span id="charCount">10</span>
As it is now, it's counting down the characters typed, from 10 to 0. I want to add some code to it, where when the page is loaded, it will show 10 (enter 3 characters minimum), and when those three characters are entered, the text in the ( ) will be gone, and only the number will be left, i.e. 7.
Also, if you erase the entered text, if character count is less than 3, the text in the ( ) to be shown again, i.e. something like this: 8 (enter 3 characters minimum)
Or even better, if it can be made like this:
10 (0 characters entered out of 3 miniumum)
9 (1 characters entered out of 3 miniumum)
8 (2 characters entered out of 3 miniumum)
7
It doesn't need to be the current code I have, suggest other code if you have.
Because noone wrote an answer, I will write one. (Even if it doesn't look like you tried it yourself.)
function characterCount(el) {
var charCount = document.getElementById('charCount');
if (el.value.length > maxLength) el.value = el.value.substring(0,maxLength);
if (charCount) charCount.innerHTML = maxLength - el.value.length;
return true;
}
to
function characterCount(el) {
var charCount = document.getElementById('charCount');
if (el.value.length > maxLength) el.value = el.value.substring(0,maxLength);
if (charCount) {
if(el.value.length < 3) {
charCount.innerHTML = (maxLength - el.value.length) + ' (' + (3 - el.value.length) + ' out of 3 characters minimum)';
} else {
charCount.innerHTML = maxLength - el.value.length;
}
}
return true;
}