JQuery allow only two numbers after decimal point - javascript
I found the following JQuery function here which prevents a user from entering anything that's not a number or a single decimal. The function works well but I'd like to improve it to prevent the user from entering 3 or more decimal places i.e. disallow 99.999 and allow 99.99. Any ideas?
function checkForInvalidCharacters(event, inputBox){
if ((event.which != 46 || inputBox.val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
};
The logic is every time a user entering a number you have to check two things.
Has the user entered decimal point?
Are the decimal places more than two?
For the first one you can use $(this).val().indexOf('.') != -1For the second one you can use $(this).val().substring($(this).val().indexOf('.'), $(this).val().indexOf('.').length).length > 2
EDIT-1
Also, you have to add event.which != 0 && event.which != 8 so that arrow keys and backspace work in Firefox (Manoj comment)
EDIT-2
Also, you have to add $(this)[0].selectionStart >= text.length - 2 so that you can add digits if the cursor is to the left of the decimal point (BIdesi comment)
EDIT-3
Also, you have to check if user deleted . and placed it somewhere else creating a value with more than 2 digits after the decimal. So you have to add
$this.val($this.val().substring(0, $this.val().indexOf('.') + 3)); for cutting extra digits (Gilberto Sánchez comment)
EDIT-4
To handle pasted data, you must bind a paste event handler.Then you have to check if pasted data have . withtext.indexOf('.') > -1 and more than 2 digits after the decimal with text.substring(text.indexOf('.')).length > 3. If so, you have to cut extra digits. Also you have to check that user entered numeric input with $.isNumeric() (darasd comment).
Here is the code:
$('.number').keypress(function(event) {
var $this = $(this);
if ((event.which != 46 || $this.val().indexOf('.') != -1) &&
((event.which < 48 || event.which > 57) &&
(event.which != 0 && event.which != 8))) {
event.preventDefault();
}
var text = $(this).val();
if ((event.which == 46) && (text.indexOf('.') == -1)) {
setTimeout(function() {
if ($this.val().substring($this.val().indexOf('.')).length > 3) {
$this.val($this.val().substring(0, $this.val().indexOf('.') + 3));
}
}, 1);
}
if ((text.indexOf('.') != -1) &&
(text.substring(text.indexOf('.')).length > 2) &&
(event.which != 0 && event.which != 8) &&
($(this)[0].selectionStart >= text.length - 2)) {
event.preventDefault();
}
});
$('.number').bind("paste", function(e) {
var text = e.originalEvent.clipboardData.getData('Text');
if ($.isNumeric(text)) {
if ((text.substring(text.indexOf('.')).length > 3) && (text.indexOf('.') > -1)) {
e.preventDefault();
$(this).val(text.substring(0, text.indexOf('.') + 3));
}
}
else {
e.preventDefault();
}
});
.number {
padding: 5px 10px;
font-size: 16px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="number" />
It can also be done with a regular expression:
$('.class').on('input', function () {
this.value = this.value.match(/^\d+\.?\d{0,2}/);
});
Name the css selector .class to whatever you like and put it on the input.
I've updated the function for a few extra cases.
It will allow negative numbers
It will allow you to edit the left of the decimal when there are already 2 digits to the right
It allows you to use the arrow keys and backspace when you are in Firefox
It also handles pasted data
/**
* Given an input field, this function will only allow numbers with up to two decimal places to be input.
* #param {object} element
* #return {number}
*/
function forceNumber(element) {
element
.data("oldValue", '')
.bind("paste", function(e) {
var validNumber = /^[-]?\d+(\.\d{1,2})?$/;
element.data('oldValue', element.val())
setTimeout(function() {
if (!validNumber.test(element.val()))
element.val(element.data('oldValue'));
}, 0);
});
element
.keypress(function(event) {
var text = $(this).val();
if ((event.which != 46 || text.indexOf('.') != -1) && //if the keypress is not a . or there is already a decimal point
((event.which < 48 || event.which > 57) && //and you try to enter something that isn't a number
(event.which != 45 || (element[0].selectionStart != 0 || text.indexOf('-') != -1)) && //and the keypress is not a -, or the cursor is not at the beginning, or there is already a -
(event.which != 0 && event.which != 8))) { //and the keypress is not a backspace or arrow key (in FF)
event.preventDefault(); //cancel the keypress
}
if ((text.indexOf('.') != -1) && (text.substring(text.indexOf('.')).length > 2) && //if there is a decimal point, and there are more than two digits after the decimal point
((element[0].selectionStart - element[0].selectionEnd) == 0) && //and no part of the input is selected
(element[0].selectionStart >= element.val().length - 2) && //and the cursor is to the right of the decimal point
(event.which != 45 || (element[0].selectionStart != 0 || text.indexOf('-') != -1)) && //and the keypress is not a -, or the cursor is not at the beginning, or there is already a -
(event.which != 0 && event.which != 8)) { //and the keypress is not a backspace or arrow key (in FF)
event.preventDefault(); //cancel the keypress
}
});
}
forceNumber($("#myInput"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="myInput" />
thank you! I have added the possibility of deleting the numbers and '.' once typed:
The event.keyCode !== 8 does that action for backspace.
The event.keyCode !== 46 does that action for delete.
$( document ).ready(function() {
$('#Ds_Merchant_Amount').keypress(function(event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57) ) {
if (event.keyCode !== 8 && event.keyCode !== 46 ){ //exception
event.preventDefault();
}
}
if(($(this).val().indexOf('.') != -1) && ($(this).val().substring($(this).val().indexOf('.'),$(this).val().indexOf('.').length).length>2 )){
if (event.keyCode !== 8 && event.keyCode !== 46 ){ //exception
event.preventDefault();
}
}
});
});
Numeric values With Decimal Point up to 2 decimal point validation.
Dependency jQuery.
HTML -
<span>Float</span>
<input type="text" name="numeric" class='allownumericwithdecimal'>
<div>Numeric values only allowed (With Decimal Point) </div>
JQuery Code -
Method 1-
$(".allownumericwithdecimal").on("keypress keyup blur", function (event) {
var patt = new RegExp(/[0-9]*[.]{1}[0-9]{2}/i);
var matchedString = $(this).val().match(patt);
if (matchedString) {
$(this).val(matchedString);
}
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
Method 2 -
$(".allownumericwithdecimal").on("keypress keyup blur", function (event) {
var patt = new RegExp(/(?<=\.\d\d).+/i);
$(this).val($(this).val().replace(patt, ''));
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
I have updated this routine to allow standard editing features as these were prevented in the above code. (This routine is just for processing a float but can be adapted to allow only 2 digits after the decimal)
var value = $(this).val().toString();
// Allowed Keys
if (event.which === 8 || event.which === 46 // Character delete
|| event.which === 16 || event.which === 17 // Modifier Key
|| event.which === 37 || event.which === 39 // Arrow Keys
|| (event.key.toLowerCase() === "a" && event.ctrlKey) // Select All
|| (event.key.toLowerCase() === "c" && event.ctrlKey) // Copy
|| (event.key.toLowerCase() === "x" && event.ctrlKey) // Cut
|| (event.key.toLowerCase() === "v" && event.ctrlKey) // Paste
|| (event.which === 45 && event.ctrlKey) // Old school copy (CTRL + INSERT)
|| (event.which === 46 && event.shiftKey) // Old school cut (SHIFT + DELETE)
|| (event.which === 45 && event.shiftKey) // Old school paste (SHIFT + INSERT)
|| (event.which === 35) // END
|| (event.which === 36) // HOME
|| (event.which === 35 && event.shiftKey) // SHIFT + END
|| (event.which === 36 && event.shiftKey) // SHIFT + HOME
)
{
return;
}
else if (event.which === 190) // Process decimal point
{
if (value == "" || value.indexOf(".") > -1)
{
event.preventDefault();
}
}
else if (event.which < 48 || event.which > 57 || event.ctrlKey || event.shiftKey) // Reject anything else that isn't a number
{
event.preventDefault();
}
Try this
HTML
<input type="text" id="min_rent" name="min_rent" onkeypress="return isPrice(event,$('#min_rent').val())">
Jquery
function isPrice(evt,value) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if((value.indexOf('.')!=-1) && (charCode != 45 && (charCode < 48 || charCode > 57)))
return false;
else if(charCode != 45 && (charCode != 46 || $(this).val().indexOf('.') != -1) && (charCode < 48 || charCode > 57))
return false;
return true;
}
Worked Link
demo
Related
Jquery to allow negative and positive numbers on text field and negative sign should have 0 indexes
I need to validate a text field to accept only negative or positive numbers and indexing also matters. this is what I have tried so far. this is HTML code <input type="text" class="negativeaccept" > here is Jquery $(document).on('keypress','.negativeaccept', function(event) { if (((event.which != 46 || (event.which == 46 && $(this).val() == '')) || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) { event.preventDefault(); } }); this code only accepts a positive number with a decimal. I want a negative sign (-) of The 0 indexes. i try this code and its working (event.which != 45 || $(this).val().indexOf('-') != -1) && but negative (-)sign enter any index. can you try this better than this a solution. $(document).on('keypress','.negativeaccept', function(event) { if (((event.which != 46 || (event.which == 46 && $(this).val() == '')) || $(this).val().indexOf('.') != -1) && (event.which != 45 || $(this).val().indexOf('-') != -1) && (event.which < 48 || event.which > 57)) { event.preventDefault(); } }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" class="negativeaccept">
How to create a textbox in html to accept only real number using jquery?
$("#chartModal").keypress( function (e) { if (e.which != 8 && e.which != 0 && e.which != 43 && e.which != 45 && e.which != 46 && (e.which < 48 || e.which > 57)) { return false; } }); This accept +, - & . in between the number, which is not a number.
Try with this $(document).ready(function () { $('#chartModal').keypress(function(e) { var key = e.charCode || e.keyCode || 0; var keychar = String.fromCharCode(key); if ( ((key == 8 || key == 9 || key == 46 || key == 35 || key == 36 || (key >= 37 && key <= 40)) && e.charCode==0) /* backspace, end, begin, top, bottom, right, left, del, tab */ || (key >= 48 && key <= 57) ) { /* 0-9 */ return; } else { e.preventDefault(); } }); });
Here is an example: $('#chartModal').keypress(function(e){ if (e.which != 8 && e.which != 0 &&e.which!= 43 && e.which!=45 && e.which !=46 &&(e.which < 48 || e.which > 57)) { return false; } var charCode = e.which; var value=$(this).val(); if(charCode==43 && value.indexOf('+')>=0) //Check whether a + is already there at beginning return false; if (charCode == 45 && value.indexOf('-') >= 0)//Check whether a - is already there at beginning return false; if (charCode == 46 && value.indexOf('.')!=-1)//Check at least one . is present in the number return false; }); Replace #idname with id of input.
Jquery Max Value Validation for Number Field
I am working on responsive Html Design. There are some number fields and they have some requirements. Control take only number After decimal it take only two digits Max value not greater than 9999999999 Max Length is 9 in case float value it will (999999.99) All validation work on key press or key up I implement this code it working fine for desktop and other mobile device but not working on any Samsung tab. If i use input type="number" then maxlength or max value not working in Samsung tab. Plz help me. CODE $("#txtnumber").keydown(function (event) { if (event.shiftKey == true) { event.preventDefault(); } if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46 || event.keyCode == 190 || event.keyCode == 110) { } else { event.preventDefault(); } if (($(this).val().indexOf('.') !== -1 && event.keyCode == 190) || $(this).val().indexOf('.') !== -1 && event.keyCode == 110)//Allow only one time decimal to input event.preventDefault(); }); $("#txtnumber").keyup(function () { var number = ($(this).val().split('.')); if (number[1].length > 2) { var FNumber = parseFloat($("#txtnumber").val()); $("#txtnumber").val(FNumber.toFixed(2)); } }); JSFiddle URL
Here is an example using jquery, $("#txtnumber").on('keyup keydown', function () { if (isNaN(($(this).val()))) { $(this).val($(this).val().substring(0, ($(this).val().length - 1))); } if ($(this).val().length > 10 && $(this).val().indexOf('.') == -1) { $(this).val($(this).val().substring(0, 10)); } if ($(this).val().indexOf('.') !== -1 && $(this).val().length > 9) { $(this).val($(this).val().substring(0, 9)); } if (($(this).val().indexOf('.') !== -1)) { var decimal = $(this).val().split('.'); if (decimal[1].length > 2) { $(this).val($(this).val().substring(0, ($(this).val().length - 1))); } } }); Updated Fiddle
allow tab and other keys in input textbox
Below is my javascript code which restrict the user for following: 1) only allow numeric and upto two decimal points. It also restrict the user for tab, backspace , delete, left and right arrow keys. I tried by adding condition event.which != 8/9/37/38 but not succeed. Below is the code: $('#txtprice').keypress(function (event) { if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) { event.preventDefault(); } var text = $(this).val(); if ((text.indexOf('.') != -1) && (text.substring(text.indexOf('.')).length > 2)) { event.preventDefault(); } }); can any one please correct me here. EDITED: Modified as below but not work. $('#txtprice').keypress(function (event) { if (event.which == 8 || event.which == 9 || event.which == 37 || event.which == 38) { event.preventDefault(); return; } if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) { event.preventDefault(); } var text = $(this).val(); if ((text.indexOf('.') != -1) && (text.substring(text.indexOf('.')).length > 2)) { event.preventDefault(); } }); Thanks
You simply just have to allow what you want, not determine what you don't want. This is easy by determining if the keyCode is a period (190) or in between 48 and 57. function validateNum(e) { var elem = document.getElementById("txtprice"); if (e.keyCode >= 48 && e.keyCode <= 57 || e.keyCode == 190) { var txt = elem.value; if (e.keyCode == 190 && txt.match(new RegExp('\\.','g')).length > 1) { e.preventDefault(); } } else { e.preventDefault(); } } Here is a working js fiddle: http://jsfiddle.net/e72uqvbv/ UPDATE: I miss understood the period situation request, I have updated my answer.
jquery only allow input float number
i'm making some input mask that allows only float number. But current problem is I can't check if multiple dots entered. Can you check those dots and prevent it for me? Live Code: http://jsfiddle.net/thisizmonster/VRa6n/ $('.number').keypress(function(event) { if (event.which != 46 && (event.which < 47 || event.which > 59)) { event.preventDefault(); if ((event.which == 46) && ($(this).indexOf('.') != -1)) { event.preventDefault(); } } });
You can check for the period in the same statement. Also, you need to use the val method to get the value of the element. Also, you want to check for the interval 48 to 57, not 47 to 59, otherwise you will also allow /, : and ;. jQuery(document).ready(function() { $('.float-number').keypress(function(event) { if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) { event.preventDefault(); } }); }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <html> <body> Enter Number: <input type="text" name="number" value="" class="float-number"> </body> </html>
I think you guys have missed the left right arrows, delete and backspace keys. $('.number').keypress(function(event) { if(event.which == 8 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 46) return true; else if((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) event.preventDefault(); });
I think everybody forgot the case of pasting text with the mouse, in which you can't detect the keystrokes, because there's none. Here's another approach I have been working on. // only integer or float numbers (with precision limit) // example element: <input type="text" value="" class="number" name="number" id="number" placeholder="enter number" /> $('.number').on('keydown keypress keyup paste input', function () { // allows 123. or .123 which are fine for entering on a MySQL decimal() or float() field // if more than one dot is detected then erase (or slice) the string till we detect just one dot // this is likely the case of a paste with the right click mouse button and then a paste (probably others too), the other situations are handled with keydown, keypress, keyup, etc while ( ($(this).val().split(".").length - 1) > 1 ) { $(this).val($(this).val().slice(0, -1)); if ( ($(this).val().split(".").length - 1) > 1 ) { continue; } else { return false; } } // replace any character that's not a digit or a dot $(this).val($(this).val().replace(/[^0-9.]/g, '')); // now cut the string with the allowed number for the integer and float parts // integer part controlled with the int_num_allow variable // float (or decimal) part controlled with the float_num_allow variable var int_num_allow = 3; var float_num_allow = 1; var iof = $(this).val().indexOf("."); if ( iof != -1 ) { // this case is a mouse paste (probably also other events) with more numbers before the dot than is allowed // the number can't be "sanitized" because we can't "cut" the integer part, so we just empty the element and optionally change the placeholder attribute to something meaningful if ( $(this).val().substring(0, iof).length > int_num_allow ) { $(this).val(''); // you can remove the placeholder modification if you like $(this).attr('placeholder', 'invalid number'); } // cut the decimal part $(this).val($(this).val().substring(0, iof + float_num_allow + 1)); } else { $(this).val($(this).val().substring(0, int_num_allow)); } return true; });
Good for integer and float values. Plus, copy/paste clipboard event. var el = $('input[name="numeric"]'); el.prop("autocomplete",false); // remove autocomplete (optional) el.on('keydown',function(e){ var allowedKeyCodesArr = [9,96,97,98,99,100,101,102,103,104,105,48,49,50,51,52,53,54,55,56,57,8,37,39,109,189,46,110,190]; // allowed keys if($.inArray(e.keyCode,allowedKeyCodesArr) === -1 && (e.keyCode != 17 && e.keyCode != 86)){ // if event key is not in array and its not Ctrl+V (paste) return false; e.preventDefault(); } else if($.trim($(this).val()).indexOf('.') > -1 && $.inArray(e.keyCode,[110,190]) != -1){ // if float decimal exists and key is not backspace return fasle; e.preventDefault(); } else { return true; }; }).on('paste',function(e){ // on paste var pastedTxt = e.originalEvent.clipboardData.getData('Text').replace(/[^0-9.]/g, ''); // get event text and filter out letter characters if($.isNumeric(pastedTxt)){ // if filtered value is numeric e.originalEvent.target.value = pastedTxt; e.preventDefault(); } else { // else e.originalEvent.target.value = ""; // replace input with blank (optional) e.preventDefault(); // retur false }; }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type="text" name="numeric" value="" placeholder="insert value"> [2017-10-31] Vanilla.js let el = document.querySelector('input[name="numeric"]'); el.addEventListener('keypress',(event) => { let k = event.key, t = isNaN(k), sc = ['Backspace'].indexOf(k) === -1, d = k === '.',dV = el.value.indexOf('.') > -1, m = k === '-',mV = el.value.length > 0; if((t && sc) && ((d && dV) || (m && dV) || (m && mV) || ((t && !d) && (t && !m)))){event.preventDefault();} },false); el.addEventListener('paste',(event) => { if(event.clipboardData.types.indexOf('text/html') > -1){ if(isNaN(event.clipboardData.getData('text'))){event.preventDefault();} } },false); <input type="text" name="numeric">
Your code seems quite fine but overcomplicated. First, it is $(this).val().indexOf, because you want to do something with the value. Second, the event.which == 46 check is inside an if clause that's only passed when event.which != 46, which can never be true. I ended up with this which works: http://jsfiddle.net/VRa6n/3/. $('.number').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 });
I found this way to do this, $.validator.addMethod("currency", function (value, element) { return this.optional(element) || /^\$(\d{1,3}(\,\d{3})*|(\d+))(\.\d{2})?$/.test(value); }, "Please specify a valid amount"); https://gist.github.com/jonkemp/9094324
HTML <input type="text" onkeypress="return isFloatNumber(this,event)" /> Javascript function isFloatNumber(item,evt) { evt = (evt) ? evt : window.event; var charCode = (evt.which) ? evt.which : evt.keyCode; if (charCode==46) { var regex = new RegExp(/\./g) var count = $(item).val().match(regex).length; if (count > 1) { return false; } } if (charCode > 31 && (charCode < 48 || charCode > 57)) { return false; } return true; } jsfiddle.net
Using JQuery. $(document).ready(function() { //Only number and one dot function onlyDecimal(element, decimals) { $(element).keypress(function(event) { num = $(this).val() ; num = isNaN(num) || num === '' || num === null ? 0.00 : num ; if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) { event.preventDefault(); } if($(this).val() == parseFloat(num).toFixed(decimals)) { event.preventDefault(); } }); } onlyDecimal("#TextBox1", 3) ; });
One-more plugin, based on Carlos Castillo answer https://github.com/nikita-vanyasin/jquery.numberfield.js Adds method to jQuery object: $('input.my_number_field').numberField(options); where options is (you can pass any or no options): { ints: 2, // digits count to the left from separator floats: 6, // digits count to the right from separator separator: "." }
Using jQuery and allowing negative floats : // Force floats in '.js_floats_only' inputs $(document).ready(function() { $('.js_floats_only').each(function() { // Store starting value in data-value attribute. $(this).data('value', this.value); }); }); $(document).on('keyup', '.js_floats_only', function() { var val = this.value; if ( val == '-' ) { // Allow starting with '-' symbol. return; } else { if ( isNaN(val) ) { // If value is not a number put back previous valid value. this.value = $(this).data('value'); } else { // Value is valid, store it inside data-value attribute. $(this).data('value', val); } } });
For simple cases and without hardcoding some html instructions would fit that pretty enough <input type="number" step="0.01"/>
$('.number').keypress(function(event){ if($.browser.mozilla == true){ if (event.which == 8 || event.keyCode == 37 || event.keyCode == 39 || event.keyCode == 9 || event.keyCode == 16 || event.keyCode == 46){ return true; } } if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) { event.preventDefault(); } }); This works in all browsers.
<input type="text" data-textboxtype="numeric" /> <script> $(document).on('keydown', '[data-textboxtype="numeric"]', function (e) { // Allow: backspace, delete, tab, escape, enter and . and - if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190, 109, 189]) !== -1 || // Allow: Ctrl+A (e.keyCode == 65 && e.ctrlKey === true) || // Allow: home, end, left, right, down, up (e.keyCode >= 35 && e.keyCode <= 40)) { // let it happen, don't do anything return true; } // Ensure that it is a number and stop the keypress if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) { e.preventDefault(); return false; } return true; }); </script>
Below Code I am allowing only Digits and Dot symbol. ASCII characters number starts in 47 and ends with 58 and dot value is 190. $("#Experince").keyup(function (event) { debugger if ((event.which > 47 && event.which < 58) ||event.which== 190) { if ($("#Experince").val().length > 3) { } } // prevent if not number/dot else { $("#Experince").val($("#Experince").val().slice(0, -1)) } });