Alow only Integer and Float values in Textfield - javascript

I have a textfield of Price.
I want only Integer and Float values in it.
I have done the Integer. But it is not accepting Float values like : 3110.6
Here is my Code DEMO
JS:
$(document).ready(function () {
$("#price").keydown(function (event) {
// Allow only backspace and delete
if (event.keyCode == 46 || event.keyCode == 8) {
// let it happen, don't do anything
} else {
// Ensure that it is a number and stop the keypress
if (event.keyCode < 48 || event.keyCode > 57) {
event.preventDefault();
}
}
});
});
HTML:
<input name="price" type="text" id="price">

try this demo
$('#price').keypress(function(event) {
if(event.which == 8 || event.which == 0){
return true;
}
if(event.which < 46 || event.which > 59) {
return false;
//event.preventDefault();
} // prevent if not number/dot
if(event.which == 46 && $(this).val().indexOf('.') != -1) {
return false;
//event.preventDefault();
} // prevent if already dot
});

Simply use this:
<input name="price" type="number" id="price">
And remove your JavaScript code.

Try regular expression
/^[+-]?\d+(\.\d+)?$/
Just test the value of the input on the onchange event.

TRy Demo dot or period has keycode 190
$(document).ready(function() {
$("#price").keydown(function(event) {
// Allow only backspace and delete
if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 190 ) {
// let it happen, don't do anything
}
else {
// Ensure that it is a number and stop the keypress
if (event.keyCode < 48 || event.keyCode > 57 ) {
event.preventDefault();
}
}
});
});
But better will be use jquery validator plugin at http://jqueryvalidation.org/ as you dont have to check yourself.
For jquery version see JQUERY VALIDATION

Related

jQuery - How can I allow both numpad and number key row input; as well as prevent special characters from being entered?

I want to allow both number pad numeric and oridinary number from keyboard. Currently, it only allows the number key row. I also only want numbers to be entered, but it currently allows special characters.
$(document).ready(function() {
$('#price').keydown(function(event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57) && event.which != 8) {
event.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='price'>
Have a look at this plug-in (Fork of texotela's numeric jquery plugin). This (jStepper) is another one.
This is a link if you want to build it yourself.
$(document).ready(function() {
$("#txtboxToFilter").keydown(function (e) {
// Allow: backspace, delete, tab, escape, enter and .
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
// Allow: Ctrl+A, Command+A
(e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
// Allow: home, end, left, right, down, up
(e.keyCode >= 35 && e.keyCode <= 40)) {
// let it happen, don't do anything
return;
}
// 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();
}
});
});
NOTE: If your webpage uses HTML5, you can use the built-in <input type="number"> and use the min and max properties to control the minimum and maximum value.
$(function() {
$('#staticParent').on('keydown', '#child', function(e){-1!==$.inArray(e.keyCode,[46,8,9,27,13,110,190])||(/65|67|86|88/.test(e.keyCode)&&(e.ctrlKey===true||e.metaKey===true))&&(!0===e.ctrlKey||!0===e.metaKey)||35<=e.keyCode&&40>=e.keyCode||(e.shiftKey||48>e.keyCode||57<e.keyCode)&&(96>e.keyCode||105<e.keyCode)&&e.preventDefault()});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="staticParent">
<input id="child" type="textarea" />
</div>
I coppied from it on here
If its help for you.Please vote first writer .
Updated your code
$(document).ready(function() {
$('#price').keydown(function(event) {
if((event.which >= 48 && event.which <= 57) && event.shiftKey) {
event.preventDefault();
}
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57) && event.which != 8) {
event.preventDefault();
}
});
});
Use keypress for that instead of keydown
then
the keyCode of 0 to 9 are 48 to 57 so use this condition
if (event.keyCode < 48 || event.keyCode > 57) {
event.preventDefault();
}
this condition returns true if you enter keys that are not 0, 1, 2, 3, 4, 5, 6, 7 ,8 and 9 or not numbers
So your code would be like this
$(document).ready(function() {
$('#price').keypress(function(event) {
if (event.keyCode < 48 || event.keyCode > 57) {
event.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='price'>
Why we don't user input type number. I think just do it easy like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='number' id='price'>

Backspace is not clearing the field in mozilla browser

I have the input box which allows only numeric.In chrome and firefox it allows only numeric but can't delete the number in using backspace in mozilla.
$(document).ready(function () {
$('#price').keypress(function(event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='price'>
Usually keypress only detects the printable keys, but the current version of Mozilla is able to detect backspace as well. Use the keydown event instead.
Demo
$(document).ready(function() {
$('#price').keydown(function(event) {
console.log(event.which);
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='price'>
Another approach Important!
Using above approach you will also have to check for other special keys like arrow keys and delete keys, not to mention if . is placed correctly and only once.
Another approach could be to simply remove non-numeric characters from the string on keyup
$(document).ready(function() {
$('#price').keyup(function(event) {
this.value = this.value.replace( /[^0-9.]/g, "" );
this.value = this.value.split(".").reduce((a,b,i)=> i > 1 ? a+b : a+"."+b );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id='price'>
It's happening because you using a wrong way to avoid backspace. There backspace 8 as key code so you have avoided this in prevent default.use this code instead.
$(document).ready(function () {
$('#price').keypress(function(event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57) && event.which != 8) {
event.preventDefault();
}
});
});
keypress event not working in firefox. you can use keyup or keydown event it will work.
$(document).ready(function () {
$('#price').keyup(function(event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57) && event.which != 8) {
event.preventDefault();
}
});
});

KeyPress and keyup in javascript

I want to allow only numbers and decimal in a inputtext field.
If I use my code in a keypress event it works fine(return false when alphabets are entered), but when i use it with keyup it is not.
My code:
function OnKeyPress(e,DivID) {
if ( e.which != 8 && e.which != 0 && e.which != 13 && e.which != 190 && (e.which < 48 || e.which > 57)) {
return false;
// event.preventDefault();
}
var val = j$('[id$='+DivID+']').val();
if(DivID == 'ProximityCPPercentage')
{
var x = event.which || event.keyCode;
if(val.indexOf('.') >= 0 && e.which == 46)
return false;
else if(e.which == 46 && val.length == 3)
return false;
if(val.indexOf('.') == 0)
val = '0' + val;
if(e.which != 46)
{
strval = val + String.fromCharCode(x);
var re = /^((.|0|[1-9]\d?)(\.\d{1})?|100(\.0?)?)$/;
if(!re.test(strval))
return false;
}
}
else if(val.indexOf('.') >= 0)
{
var reg =/^(\d{0,4}\.?(\d{0,1})|\d{0,6})?$/gm;
if(!reg.test(val))
{
j$('[id$='+DivID+']').val(val.substring(0, val.length - 1));
}
}
else if(e.which != 190 )
{
if(val.length > 5)
return false;
}
}
If I use this function in onkeypress attribute of input field it is not allowing alphabets but when i use in onkeyup it does allows the alphabets.
Ok, I created a simple fiddle with an explanation of what is happening for you https://jsfiddle.net/gb0kwom0/3/
On key down, will capture the event before a value is set in the input (result: alert fire then nothing in input value), see this example.
<input type="text" onkeypress="return onPress()">
<script>
function onPress(){alert(); return false;}
</script>
On key up, will capture the event after a value is set in the input (result: value set then alert will fire), see this example.
<input type="text" onkeyup="return onUp()">
<script>
function onUp(){alert(); return false;}
</script>
So to solve your issue onKeyUp you will need to reset the value.
The result will be: will capture the event after a value is set in the input then reset the value back to empty, see this example.
note: this example is just to show the difference and should not be used, it will reset the whole value back to nothing
<input type="text" onkeyup="onUp2(this)">
<script>
function onUp2(obj){alert(); obj.value='';}
</script>
this method is not ideal and will take a lot more code to get working, it is why you should continue to use onkeypress instead

Jquery Script Not Working to accept input numbers only

I have written my Jquery script to input number only for textbox.
Following is my html code :
<input type="text" name="mobile_number" id="mobile_number" maxlength="10" class="form-control input-md" placeholder="Mobile Number" required="required">
When I try to input some value it accepts both numbers and characters also.
My Jquery Script is :
$("#mobile_number").keydown(function(event) {
if ( event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 ) {
}
else {
if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105 )) {
event.preventDefault();
}
} });
$(document).ready(function () {
//called when key is pressed in textbox
$("mobile_number").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
//display error message
$("#errmsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
});
http://jsfiddle.net/lesson8/HkEuf/1/
I have updated the code here check this out it works as expected .
Or, you could try an existing solution,
like this one: http://firstopinion.github.io/formatter.js/demos.html
or this one: http://www.decorplanit.com/plugin/
Check that you have included any version of jquery, also write your code in $(document).ready() like,
$(function () {
$("#mobile_number").keydown(function (event) {
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9) {
} else {
if ((event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
event.preventDefault();
}
}
});
});
Demo
the range of keyCode for numbers is [95,105]; and [48,57]
$("#mobile_number").keydown(function(event) {
if ( (event.keyCode > 95 && event.keyCode <106)||(event.keyCode > 47 && event.keyCode <58)) {
}
else {
event.preventDefault();
}
});
I use this OneLiner
<input type="number" onkeypress="return /[0-9]/i.test(event.key)">
Or
<input type="text" onkeypress="return /[0-9]/i.test(event.key)">

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))
}
});

Categories