How to allow only one "." in javascript during Keypress?
I have a code here:
function allowOneDot(txt) {
if ((txt.value.split(".").length) > 1) {
//here, It will return false; if the user type another "."
}
}
I will reiterate what I said in my comment before the answer:
And what if the user pastes in a bunch of periods? What if they edit the javascript in their console to completely ignore this check? Make sure you are handling validation correctly and not making too many simplifications.
Now that we're proceeding at our own risk, here's how you would not allow a user typing more than one . (period) in a textbox:
document.getElementById('yourTextboxIDHere').onkeypress = function (e) {
// 46 is the keypress keyCode for period
// http://www.asquare.net/javascript/tests/KeyCode.html
if (e.keyCode === 46 && this.value.split('.').length === 2) {
return false;
}
}
Working demo
If you really want to allow one dot, even in the event of a user pasting text inside it, you should use keyup, not keypress, and you could keep your last text value in case you need to restore it.
The drawback though, is that the input value will have already been changed, and you will see it getting corrected as you type.
(function() {
var txt = document.getElementById('txt');
var prevValue = txt.value;
function allowOneDot(e) {
var dots = 0;
var length = txt.value.length;
var text = txt.value;
for(var i=0; i<length; i++) {
if(text[i]=='.') dots++;
if(dots>1) {
txt.value = prevValue;
return false;
}
}
prevValue = text;
return true;
}
txt.onkeyup = allowOneDot;
})();
I solved this question for the multipurpose use of decimal, number & alphanumeric field types.
For field types 'number' and 'alphanum', parameter l (lower L) is the string length allowed. For type 'decimal', it specifies the allowed number of decimal places.
function allowType(e, o = 'number', l = false) {
let val = e.target.value;
switch (o) {
case 'alphanum':
if (l) {
val = val.substr(0, l).replaceAll(/[^0-9a-zA-Z]/gmi, '');
} else {
val = val.replaceAll(/[^0-9a-zA-Z]/gmi, '');
}
break;
case 'number':
if (l) {
val = val.substr(0, l).replaceAll(/[^0-9]/gmi, '');
} else {
val = val.replaceAll(/[^0-9]/gmi, '');
}
break;
case 'decimal':
let i = val.search(/\./gmi);
if (val.length === 1) {
val = val.replaceAll(/[^0-9]/gmi, '');
}
if (i >= 0) {
if (l) {
val = val.substr(0, i + 1) + val.substr(i).substr(0, l + 1).replaceAll(/\./gmi, '');
} else {
val = val.substr(0, i + 1) + val.substr(i).replaceAll(/\./gmi, '');
}
}
val = val.replaceAll(/[^0-9.]/gmi, '');
break;
}
e.target.value = val;
}
<input type="text" oninput="allowType(event, 'decimal', 2)" placeholder="decimal">
<input type="text" oninput="allowType(event, 'number', 10)" placeholder="number">
<input type="text" oninput="allowType(event, 'alphanum', 5)" placeholder="alphanumeric">
<input type="text" id="test" onkeyup="floatOnly(this);"/>
<script>
function floatOnly(i){
{
if ((i.value).length > 0){else{i.value = i.value.replace(".." , ".");i.value = i.value.replace("..." , ".");i.value = i.value.replace(/[^0-9\.]/g , "");}}else{i.value = i.value="0";}}<script>
Related
I have got a task to prevent keypress two digits after a decimal number.
My jquery file is
$(function(){
$('#name').bind('paste', function(){
var self = this;
setTimeout(function() {
if(!/^[a-zA-Z]+$/.test($(self).val()))
$(self).val('');
}, 0);
});
$('#salary').bind('paste', function(){
var self = this;
setTimeout(function() {
if(!/^\d*(\.\d{1,2})+$/.test($(self).val()))
$(self).val('');
}, 0);
});
$('.decimal').keyup(function(){
var val = $(this).val();
if(isNaN(val)){
val = val.replace(/[^0-9]./g,'');
if(val.split('.').length>2)
val =val.replace(/\.+$/,"");
}
$(this).val(val);
});
});
My html page is
<b>Name</b>
<input type="text" id="name" /><br/>
<b>Salary</b>
<input type="text" id="salary" class="decimal" />
here i want only write 2 digits after decimal,how can i do this?
You can see my code in http://jsfiddle.net/V6s4B/
You can handle the key event before keyup on keypress, if the input is not to our liking we can disable the event from occurring. Something like this:
Update
Unfortunately my original answer below fails on certain numbers that can't be represented accurately as a float. Here is another solution that checks the position of the '.' character against the length of the string with a handy helper function.
jsFiddle
$('.decimal').keypress(function (e) {
var character = String.fromCharCode(e.keyCode)
var newValue = this.value + character;
if (isNaN(newValue) || hasDecimalPlace(newValue, 3)) {
e.preventDefault();
return false;
}
});
function hasDecimalPlace(value, x) {
var pointIndex = value.indexOf('.');
return pointIndex >= 0 && pointIndex < value.length - x;
}
Original answer
jsFiddle
$('.decimal').keypress(function (e) {
var character = String.fromCharCode(e.keyCode)
var newValue = this.value + character;
if (isNaN(newValue) || parseFloat(newValue) * 100 % 1 > 0) {
e.preventDefault();
return false;
}
});
Note that parseFloat(newValue) * 100 % 1 > 0 evaluates to true if newValue contains a number that has more than 2 decimal places.
$("#salary").keyup(function(){
var number = ($(this).val().split('.'));
if (number[1].length > 2)
{
var salary = parseFloat($("#salary").val());
$("#salary").val( salary.toFixed(2));
}
});
http://jsfiddle.net/calder12/fSQpc/
Stop letters from going in the box, you'll have to put the two together I haven't time.
if (this.value.match(/[^0-9]./g)) {
this.value = this.value.replace(/[^0-9]./g, '');
return false;
}
Another Possible Solution(Demo):
Number.prototype.toFixedDown = function(digits) {
var n = this - Math.pow(10, -digits)/2;
n += n / Math.pow(2, 53); // added 1360765523: 17.56.toFixedDown(2) === "17.56"
return n.toFixed(digits);
}
$( function() {
$('.two-digits').keyup(function(){
if($(this).val().indexOf('.')!=-1){
if($(this).val().split(".")[1].length > 2){
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixedDown(2);
}
}
return this; //for chaining
});
});
This might be helpful to some. I mixed the answers of this guy, #Tats_innit
from https://stackoverflow.com/a/10514166/5382523 and #Rick Calder above.
EDIT
also from this guy, isJustMe from https://stackoverflow.com/a/17289322
for the parseFloat with "|| 0". Because if the input's field is null or zero "NaN" is shown and you can't delete it.
HTML
<input type="text" name="txt_prod_price" id="txt_prod_price" class="form-control price" maxlength="20" placeholder="">
JAVASCRIPT (JQUERY)
$('.price').keypress(function(event) {
if(event.which < 46 || event.which > 59) {
event.preventDefault();
} // prevent if not number/dot
if(event.which == 46 && $(this).val().indexOf('.') != -1) {
event.preventDefault();
} // prevent if already dot
var number = ($(this).val().split('.'));
if (number[1].length > 2)
{
var price = parseFloat($("#txt_prod_price").val()) || 0;
$("#txt_prod_price").val(price.toFixed(2));
}
});
the "price" is pre-defined.
Note: still have buggy inputs but still kickin'. (y)
More info about toFixed - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
I did it this way: Provided a class allow-only-numbers, for your input then:
var numberOfDecimals = 2;
$(document).on("input", ".allow-only-numbers", function () {
var regExp = new RegExp('(\\.[\\d]{' + numberOfDecimals + '}).', 'g')
this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1').replace(regExp, '$1');
});
How to validate in an Amount input field?
Allow minus (Negative) sign only once in the text box. For, eg, -10.00. Don't allow other special characters because it's an amount field.
It should not allow alphabet letters. Allow only numbers.
Decimal(.) should be only once in the text box.
I've wrote this just now based on your conditions, test it below:
Update:
Modified to work both on jquery and in javascript inline
// This is a middleware that takes as parameter "decimals" which is by default 2
currencyNumber = function(decimals) {
if (typeof decimals !== 'number') {
decimals = 2;
}
return function(e) {
var input = $(this instanceof Window ? e : e.currentTarget);
var value = $.trim(input.val());
var hasNegativeNumber = value.substr(0, 1) === '-' ? '-' : '';
var nextValue = value
.replace(/\.+/g, '.')
.replace(/[^0-9\.]+/g, '');
if (nextValue === '.' || (nextValue.length > 1 && nextValue === "00")) {
nextValue = '';
}
var dotsFound = nextValue.split('.').filter(function(i) {
return i.length;
});
var afterDot = '';
var beforeDot = '';
if (dotsFound.length > 1) {
beforeDot = dotsFound[0];
dotsFound.splice(0, 1);
afterDot = dotsFound.join('');
nextValue = +(beforeDot) + '.' + afterDot.substr(0, decimals);
}
if (nextValue.substr(nextValue.length - 1, 1) === '.') {
input.one('change', function() {
if (nextValue.substr(nextValue.length - 1, 1) === '.') {
nextValue = nextValue.substr(0, nextValue.length - 1);
input.val(hasNegativeNumber + nextValue);
}
$(this).off('change');
})
} else {
input.off('change')
}
input.val(hasNegativeNumber + nextValue);
};
}
// Here is where you call the middleware
$("#amount").on("keyup", currencyNumber(3));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="banner-message">
Test your number (bind is from jquery):
<input id="amount" type='text' />
<br /> Test your number (bind is from javascript inline):
<input id="amount-inline" onkeyup="currencyNumber(3)(this);" type='text' />
</div>
Edited: I guess this is what you are looking for. Found this in jsfiddle.net. No plugin needed.
HTML:
<input type="text" maxlength="10" id="myInput">
Javascript
var input = document.getElementById("myInput");
input.onkeypress = function(e) { e = e || window.event;
var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
// Allow non-printable keys
if (!charCode || charCode == 8 /* Backspace */ ) {
return;
}
var typedChar = String.fromCharCode(charCode);
// Allow numeric characters
if (/\d/.test(typedChar)) {
return;
}
// Allow the minus sign (-) if the user enters it first
if (typedChar == "-" && this.value == "") {
return;
}
// In all other cases, suppress the event
return false;
};
What I am trying to do is to apply some validation on an input text field based on a checkbox and whether it is checked or not.
Case 1: when check box is selected, user can only enter numbers from 0 to 100 (decimal included. So 34.35 is allowed)
Case 2: Normal numeric validation
However the behavior of my code in Case 1 is it only allow user to enter 1 nu,beric digit between 1 to 9.
Here is my code.
HTML markup
elements.stakeInput = $('<input placeholder="0.00" type="text" style="float:right" />');
elements.promoMoneyCheckbox = $('<input type="checkbox" />');
JS
elements.promoMoneyCheckbox.click(function() {
SingleDiv.prototype.validatePromoInputField(self);
});
validatePromoInputField : function(singleDiv) {
var self = this,
elements = singleDiv.getElements(),
promoMoneyCheckbox = elements.promoMoneyCheckbox;
if (promoMoneyCheckbox.is(':checked')) {
elements.stakeInput.attr("placeholder", "10.00");
elements.stakeInput.keypress(function(event) {
var num = parseInt(self.value, 10),
min = 0,
max = 100;
if (isNaN(num)) {
this.value = "";
return;
}
this.value = Math.max(num, min);
this.value = Math.min(num, max);
})
}
else {
elements.stakeInput.attr("placeholder", "00.00");
validateInputs(event, 'decimal')
}
}
function validateInputs(event, typeOfInput) {
event = event || window.event;
if (event.ctrlKey || event.altKey || event.metaKey) return;
var regex;
switch (typeOfInput) {
case 'decimal':
regex = /^[.0-9]$/;
break;
case 'minAndMax':
regex = // May be I could add a regex over here instead of the validating in validatePromoInputField fucntion
break;
default:
regex = /^.$/;
break;
}
var char = getKeypressChar(event);
if (char == null || regex.test(char)) return;
event.preventDefault ? event.preventDefault() : (event.returnValue = false);
}
Is there any simple way to achieve this?
I am not looking for HTML5 validation i.e (input type="number" min and max value).
Use jquery .change() event to detect changes of the input and parseInt to verify the input.
$("#in").change(function(e) {
var val = parseInt($(this).val());
if (!isNaN(val)) {
if (val >= 0 && val < 100) {
$("#out").html("good!");
return;
}
}
$("#out").html("bad!");
});
http://jsfiddle.net/VxM4h/1/
Remember that client side changes can be altered. Make sure to verify your input on the server side as well.
I have got a task to prevent keypress two digits after a decimal number.
My jquery file is
$(function(){
$('#name').bind('paste', function(){
var self = this;
setTimeout(function() {
if(!/^[a-zA-Z]+$/.test($(self).val()))
$(self).val('');
}, 0);
});
$('#salary').bind('paste', function(){
var self = this;
setTimeout(function() {
if(!/^\d*(\.\d{1,2})+$/.test($(self).val()))
$(self).val('');
}, 0);
});
$('.decimal').keyup(function(){
var val = $(this).val();
if(isNaN(val)){
val = val.replace(/[^0-9]./g,'');
if(val.split('.').length>2)
val =val.replace(/\.+$/,"");
}
$(this).val(val);
});
});
My html page is
<b>Name</b>
<input type="text" id="name" /><br/>
<b>Salary</b>
<input type="text" id="salary" class="decimal" />
here i want only write 2 digits after decimal,how can i do this?
You can see my code in http://jsfiddle.net/V6s4B/
You can handle the key event before keyup on keypress, if the input is not to our liking we can disable the event from occurring. Something like this:
Update
Unfortunately my original answer below fails on certain numbers that can't be represented accurately as a float. Here is another solution that checks the position of the '.' character against the length of the string with a handy helper function.
jsFiddle
$('.decimal').keypress(function (e) {
var character = String.fromCharCode(e.keyCode)
var newValue = this.value + character;
if (isNaN(newValue) || hasDecimalPlace(newValue, 3)) {
e.preventDefault();
return false;
}
});
function hasDecimalPlace(value, x) {
var pointIndex = value.indexOf('.');
return pointIndex >= 0 && pointIndex < value.length - x;
}
Original answer
jsFiddle
$('.decimal').keypress(function (e) {
var character = String.fromCharCode(e.keyCode)
var newValue = this.value + character;
if (isNaN(newValue) || parseFloat(newValue) * 100 % 1 > 0) {
e.preventDefault();
return false;
}
});
Note that parseFloat(newValue) * 100 % 1 > 0 evaluates to true if newValue contains a number that has more than 2 decimal places.
$("#salary").keyup(function(){
var number = ($(this).val().split('.'));
if (number[1].length > 2)
{
var salary = parseFloat($("#salary").val());
$("#salary").val( salary.toFixed(2));
}
});
http://jsfiddle.net/calder12/fSQpc/
Stop letters from going in the box, you'll have to put the two together I haven't time.
if (this.value.match(/[^0-9]./g)) {
this.value = this.value.replace(/[^0-9]./g, '');
return false;
}
Another Possible Solution(Demo):
Number.prototype.toFixedDown = function(digits) {
var n = this - Math.pow(10, -digits)/2;
n += n / Math.pow(2, 53); // added 1360765523: 17.56.toFixedDown(2) === "17.56"
return n.toFixed(digits);
}
$( function() {
$('.two-digits').keyup(function(){
if($(this).val().indexOf('.')!=-1){
if($(this).val().split(".")[1].length > 2){
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixedDown(2);
}
}
return this; //for chaining
});
});
This might be helpful to some. I mixed the answers of this guy, #Tats_innit
from https://stackoverflow.com/a/10514166/5382523 and #Rick Calder above.
EDIT
also from this guy, isJustMe from https://stackoverflow.com/a/17289322
for the parseFloat with "|| 0". Because if the input's field is null or zero "NaN" is shown and you can't delete it.
HTML
<input type="text" name="txt_prod_price" id="txt_prod_price" class="form-control price" maxlength="20" placeholder="">
JAVASCRIPT (JQUERY)
$('.price').keypress(function(event) {
if(event.which < 46 || event.which > 59) {
event.preventDefault();
} // prevent if not number/dot
if(event.which == 46 && $(this).val().indexOf('.') != -1) {
event.preventDefault();
} // prevent if already dot
var number = ($(this).val().split('.'));
if (number[1].length > 2)
{
var price = parseFloat($("#txt_prod_price").val()) || 0;
$("#txt_prod_price").val(price.toFixed(2));
}
});
the "price" is pre-defined.
Note: still have buggy inputs but still kickin'. (y)
More info about toFixed - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed
I did it this way: Provided a class allow-only-numbers, for your input then:
var numberOfDecimals = 2;
$(document).on("input", ".allow-only-numbers", function () {
var regExp = new RegExp('(\\.[\\d]{' + numberOfDecimals + '}).', 'g')
this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1').replace(regExp, '$1');
});
JS Bin demo
This regex transform each lower case word to upper case. I have a full name input field. I do want the user to see that each word's first letter he/she pressed is converted to uppercase in the input field.
I have no idea how to properly replace the selected characters in the current input field.
$('input').on('keypress', function(event) {
var $this = $(this),
val = $this.val(),
regex = /\b[a-z]/g;
val = val.toLowerCase().replace(regex, function(letter) {
return letter.toUpperCase();
});
// I want this value to be in the input field.
console.log(val);
});
Given i.e: const str = "hello world" to become Hello world
const firstUpper = str.substr(0, 1).toUpperCase() + str.substr(1);
or:
const firstUpper = str.charAt(0).toUpperCase() + str.substr(1);
or:
const firstUpper = str[0] + str.substr(1);
input {
text-transform: capitalize;
}
http://jsfiddle.net/yuMZq/1/
Using text-transform would be better.
You can convert the first letter to Uppercase and still avoid the annoying problem of the cursor jumping to the beginning of the line, by checking the caret position and resetting the caret position. I do this on a form by defining a few functions, one for all Uppercase, one for Proper Case, one for only Initial Uppercase... Then two functions for the Caret Position, one that gets and one that sets:
function ProperCase(el) {
pos = getInputSelection(el);
s = $(el).val();
s = s.toLowerCase().replace(/^(.)|\s(.)|'(.)/g,
function($1) { return $1.toUpperCase(); });
$(el).val(s);
setCaretPosition(el,pos.start);
}
function UpperCase(el) {
pos = getInputSelection(el);
s = $(el).val();
s = s.toUpperCase();
$(el).val(s);
setCaretPosition(el,pos.start);
}
function initialCap(el) {
pos = getInputSelection(el);
s = $(el).val();
s = s.substr(0, 1).toUpperCase() + s.substr(1);
$(el).val(s);
setCaretPosition(el,pos.start);
}
/* GETS CARET POSITION */
function getInputSelection(el) {
var start = 0, end = 0, normalizedValue, range,
textInputRange, len, endRange;
if (typeof el.selectionStart == 'number' && typeof el.selectionEnd == 'number') {
start = el.selectionStart;
end = el.selectionEnd;
} else {
range = document.selection.createRange();
if (range && range.parentElement() == el) {
len = el.value.length;
normalizedValue = el.value.replace(/\r\n/g, "\n");
// Create a working TextRange that lives only in the input
textInputRange = el.createTextRange();
textInputRange.moveToBookmark(range.getBookmark());
// Check if the start and end of the selection are at the very end
// of the input, since moveStart/moveEnd doesn't return what we want
// in those cases
endRange = el.createTextRange();
endRange.collapse(false);
if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
start = end = len;
} else {
start = -textInputRange.moveStart("character", -len);
start += normalizedValue.slice(0, start).split("\n").length - 1;
if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
end = len;
} else {
end = -textInputRange.moveEnd("character", -len);
end += normalizedValue.slice(0, end).split("\n").length - 1;
}
}
}
}
return {
start: start,
end: end
};
}
/* SETS CARET POSITION */
function setCaretPosition(el, caretPos) {
el.value = el.value;
// ^ this is used to not only get "focus", but
// to make sure we don't have it everything -selected-
// (it causes an issue in chrome, and having it doesn't hurt any other browser)
if (el !== null) {
if (el.createTextRange) {
var range = el.createTextRange();
range.move('character', caretPos);
range.select();
return true;
}
else {
// (el.selectionStart === 0 added for Firefox bug)
if (el.selectionStart || el.selectionStart === 0) {
el.focus();
el.setSelectionRange(caretPos, caretPos);
return true;
}
else { // fail city, fortunately this never happens (as far as I've tested) :)
el.focus();
return false;
}
}
}
}
Then on document ready I apply a keyup event listener to the fields I want to be checked, but I only listen for keys that can actually modify the content of the field (I skip "Shift" key for example...), and if user hits "Esc" I restore the original value of the field...
$('.updatablefield', $('#myform')).keyup(function(e) {
myfield=this.id;
myfieldname=this.name;
el = document.getElementById(myfield);
// or the jquery way:
// el = $(this)[0];
if (e.keyCode == 27) { // if esc character is pressed
$('#'+myfield).val(original_field_values[myfield]); // I stored the original value of the fields in an array...
// if you only need to do the initial letter uppercase, you can apply it here directly like this:
initialCap(el);
} // end if (e.keyCode == 27)
// if any other character is pressed that will modify the field (letters, numbers, symbols, space, backspace, del...)
else if (e.keyCode == 8||e.keycode == 32||e.keyCode > 45 && e.keyCode < 91||e.keyCode > 95 && e.keyCode < 112||e.keyCode > 185 && e.keyCode < 223||e.keyCode == 226) {
// if you only need to do the initial letter uppercase, you can apply it here directly like this:
initialCap(el);
} // end else = if any other character is pressed //
}); // end $(document).keyup(function(e)
You can see a working fiddle of this example here: http://jsfiddle.net/ZSDXA/
Simply put:
$this.val(val);
$(document).ready(function() {
$('input').on('keypress', function(event) {
var $this = $(this),
val = $this.val();
val = val.toLowerCase().replace(/\b[a-z]/g, function(letter) {
return letter.toUpperCase();
});
console.log(val);
$this.val(val);
});
});
As #roXon has shown though, this can be simplified:
$(document).ready(function() {
//alert('ready');
$('input').on('keypress', function(event) {
var $this = $(this),
val = $this.val();
val = val.substr(0, 1).toUpperCase() + val.substr(1).toLowerCase();
$this.val(val);
});
});
An alternative, and better solution in my opinion, would be to only style the element as being capitalized, and then do your logic server side.
This removes the overhead of any javascript, and ensures the logic is handled server side (which it should be anyway!)
$('input').on('keyup', function(event) {
$(this).val(function(i, v){
return v.replace(/[a-zA-Z]/, function(c){
return c.toUpperCase();
})
})
});
http://jsfiddle.net/AbxVx/
This will do for every textfield call function on keyup
where id is id of your textfield and value is value you type in textfield
function capitalizeFirstLetter(value,id)
{
if(value.length>0){
var str= value.replace(value.substr(0,1),value.substr(0,1).toUpperCase());
document.getElementById(id).value=str;
}
}
only use this This work for first name in capital char
style="text-transform:capitalize;
Like
<asp:TextBox ID="txtName" style="text-transform:capitalize;" runat="server" placeholder="Your Name" required=""></asp:TextBox>
$('.form-capitalize').keyup(function(event) {
var $this = $(this),
val = $this.val(),
regex = /\b[a-z]/g;
val = val.toLowerCase().replace(regex, function(letter) {
return letter.toUpperCase();
});
this.value = val;
// I want this value to be in the input field.
console.log(val);
});