Don't want decimal value in the input field - javascript

I dont want to allow the decimal values in text box.. I have written the code but it works only if you remove the whole value and then reinsert it..
My issue is when I try to edit the existing value it take the decimal numbers..
Here's the jsfiddle. This is code for reference:
HTML
<input id="Amt" type="text" value="$78.00">
jQuery
$(document).ready(function () {
$("#Amt").keydown(function (e) {
if ((!e.shiftKey && !e.ctrlKey && !e.altKey) && ((e.keyCode >= 48 && e.keyCode <= 57) ||
(e.keyCode >= 96 && e.keyCode <= 105))) {
}
else if (e.keyCode != 8 && e.keyCode != 46 && e.keyCode != 37 && e.keyCode != 39 &&
e.keyCode != 9) {
e.preventDefault();
}
});
$("#Amt").keyup(function (e) {
var value = $(this).val();
var newValue = parseFloat(value).toFixed(2);
if (!isNaN(newValue)) {
$(this).val(newValue);
$(this).caret(newValue.length - 3, newValue.length - 3);
}
});
});

You can use string methods to chop out the decimal and re-append '.00' if you want to keep this format.
$("#Amt").blur(function (e) {
var value = this.value.replace(/\$/g,"");
var dotPos = value.indexOf(".");
var dollars = dotPos>-1?value.substring(0,dotPos):value;
$(this).val(dollars+".00");
});
$("#Amt").blur();
http://jsfiddle.net/ZUj8M/14/

I would go about it in a completely different way, just prevent the decimal from getting there in the first place. http://jsfiddle.net/ZUj8M/7/
$(document).ready(function () {
var timer;
$("#Amt").on("keydown paste input",function (e) {
var el = this,
origval = this.value;
clearTimeout(timer);
timer = setTimeout(function () {
if (origval != el.value && /\./.test(el.value)) {
el.value = origval;
alert("Decimals are not allowed in this field.");
}
}, 0);
});
if (/\./.test($("#Amt").val())) {
$("#Amt").val($("#Amt").val().replace(/\./g,""));
}
});
alternatively you could instead of undoing the change, simply remove the decimal.
// el.value = origval;
// alert("Decimals are not allowed in this field.");
el.value = el.value.replace(/\./g,"");

why not parsing the given value to Integer?
var newValue = parseInt(floatValue, 10);
then allow the users to insert a dot "." and on .blur()-event you can parse the float to int...
$("#Amt").blur(function() {
$this.val(parseInt(jQuery(this).val(), 10));
});

Related

Gave regex for allowing only alphabets and a space but its not validating for numpad

Althought I've given regex for name its allowing numpad numbers. Similar issue in mobile number field, its allowing special characters although I've given regex. Why is this not working? Any help would be appreciated
let namecheck = false;
let mobcheck = false;
$("#fname").keydown(function (ev) {
var namekey = String.fromCharCode(ev.which);
var input = this.value
var prev = input.length - 1
let nameregex = /^[A-Za-z ]$/
if (ev.which != 8 && ev.which != 46) { //to allow backspace and del
if (!nameregex.test(namekey) || (input[prev] == " " && namekey == " ")) {
ev.preventDefault();
}
}
if (input.length < 2) {
namecheck = false
$("#error1").text("Enter at least 3 characters")
}
else {
$("#error1").text("")
namecheck = true
}
})
$("#fmob").keydown(function (ev) {
let mobkey = String.fromCharCode(ev.which)
let mob = this.value;
let mobregex = /^[0-9]$/
if (ev.which != 8 && ev.which != 46) { //to allow backspace and del
if (!mobregex.test(mobkey)) {
ev.preventDefault()
}
}
if (mob.length < 9) {
$("#error2").text("Mobile number should be at least 10 digits")
mobcheck = false
}
if (mob.length == 9) {
$("#error2").text("")
mobcheck = true
}
if (mob.length == 10) {
if (ev.which != 8 && ev.which != 46) {
ev.preventDefault()
}
}
})
})
Regex expression will not prevent numpad it seems. I would suggest you check the codes 96 through 105 if you want to block 0-9 on the numpad.
Prevent numpad:
if (ev.which >= 96 && ev.which <= 105) {
ev.preventDefault();
}
Use event.key to get the actual key so the regex number will not accept letters or special characters.
const key = ev.key
const numberReg = /^[0-9]$/
if(!numberReg.test(key)){
// prevent letters and special cahracters
ev.preventDefault()
}

Disable first character in textbox

I have a textbox and it contain a value "Given Name". I want to disable first character of a textbox so that user cannot change the First Charcter in textbox by using backspace or any other means.
For Example: suppose textbox contains the value "Given Name". I want that user cannot change the First character "G" by using backspace or any other means.
<input type="text" id="nameId" onkeydown="validate(this.val)"/>
Below is javascript function:
function validate2(val) {
// have no idea how to do.
}
I have no idea how to do it in Javscript or Jquery.
You could do like follow :
$("#nameId").on("keydown", function(e) {
// if user writes a char at index === 0 that is not an arrow or HOME or END
if (($(this).get(0).selectionStart === 0 && (e.keyCode < 35 || e.keyCode > 40))
// or if user tries to erase first char
|| ($(this).get(0).selectionStart === 1 && $(this).get(0).selectionEnd === 1 && e.keyCode === 8)) {
// don't write the character
return false;
}
});
// prevent right click
$("#nameId").bind("contextmenu", function(e) {
e.preventDefault();
});
JSFIDDLE
Wasn't planning on answering, leaving it with the comment, but after seeing the other answers thought I might have a quick go at it after all:
The html:
<input type="text" id="nameId" value="Given Name" onkeydown="save(this,event)" onkeyup="restore(this,event)" onchange="restore(this,event)"/>
The javascript:
function restore(el,event) {
if(el.value.length == 0){
el.value = el.dataset.value.substr(0,1);
}else{
el.dataset.value = el.value;
}
}
function save(el,event) {
var key = event.which || event.charCode || event.keyCode;
if((key === 8 && el.value.length === 1)
|| (key === 46 && el.selectionStart == 0 && el.value.length === 1)){
event.preventDefault();
}
if(el.value.length > 0){
el.dataset.value = el.value;
}
}
The approach was to not mess around too much with preventing the deletion of the actual character (just the very bare basics) and instead ensure that if somebody deletes the first character to always restore it somehow. It creates code that's easy to comprehend and maintain, yet works quite neatly. A fiddle can be found here as well. Do note though that event.which is not the most cross browser consistent interface, so either use jQuery for that or check in other browsers before using it in production. Edited it in a way that should work cross browser including older browsers.
Here's mine version.
Html
<input type="text" id="nameId" value="Given Name" />
JS
var lastentry = '';
$("#nameId").on("keyup", function(e) {
var targetValue = $(e.currentTarget).attr('value');
var targetValueLength = targetValue.length;
var inputValue = this.value;
if(checkChanges(targetValueLength, targetValue, inputValue))
this.value = targetValue + lastentry;
else
lastentry = this.value.slice(targetValueLength)
});
function checkChanges(targetValueLength, targetValue, inputValue)
{
for(var i = 0; i < targetValueLength ; i++)
{
if(targetValue[i] != inputValue[i])
return true;
}
return false;
}
Demo
You can try this:-
<input type="text" id="nameId" value="Given Name" onkeydown="validate(this.value,event)"/>
<script>
function validate(val,event) {
// have no idea how to do.
if(event.target.selectionStart != undefined && (event.which === 46 ||event.which === 8)){
var startPos = event.target.selectionStart,
endPos = event.target.selectionEnd;
console.log(startPos,endPos);
if(startPos === 0 && startPos != endPos){
var restPart = val.slice(endPos,val.length);
if(restPart){
val = val[0].concat(restPart);
} else{
val = val[0]
}
event.target.value = val;
event.preventDefault();
} else if(startPos === 0 && startPos === endPos && event.which === 46){
event.preventDefault();
} else if(startPos === 1 && event.which === 8){
event.preventDefault();
}
}
}
</script>
Hi use this it do not allow to delete first character ,
$(document).keydown(function(e)
{
var value = $('#nameId').val().length;
if ( e.keyCode == 8 && value < 2)
e.preventDefault();
});

make an input only-numeric type on knockout

i read many tutorials but i dont know how to do this, this is the input
input(type="text",name="price",id="price"data-bind="text: price,valueUpdate:['afterkeydown','propertychange','input']")
and this is my viewModel
price: ko.computed(function()
{
return parseFloat(this.replace(' ','').replace(/[^0-9\.]+/g,"")) || '';
},this)
but this cause error: this has no method replace??? how can i pass the price value to the computed function??
Is better to create custom binding http://knockoutjs.com/documentation/custom-bindings.html which accept only allowed characters [0-9,.] as numeric representation.
put this line into your view
<input id="text" type="text" data-bind="numeric, value: number">
put this line into your model (remember to bind number as observable property)
ko.bindingHandlers.numeric = {
init: function (element, valueAccessor) {
$(element).on("keydown", function (event) {
// Allow: backspace, delete, tab, escape, and enter
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: . ,
(event.keyCode == 188 || event.keyCode == 190 || event.keyCode == 110) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
else {
// Ensure that it is a number and stop the keypress
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
event.preventDefault();
}
}
});
}
};
Knockout has extenders for this. Check This from knockoutjs.com explaining how to use observable extenders to force input to be numeric. I paste the code from the documentation here:
Source code: View
<p><input data-bind="value: myNumberOne" /> (round to whole number)</p>
<p><input data-bind="value: myNumberTwo" /> (round to two decimals)</p>
Source code: View model
ko.extenders.numeric = function(target, precision) {
//create a writable computed observable to intercept writes to our observable
var result = ko.pureComputed({
read: target, //always return the original observables value
write: function(newValue) {
var current = target(),
roundingMultiplier = Math.pow(10, precision),
newValueAsNum = isNaN(newValue) ? 0 : parseFloat(+newValue),
valueToWrite = Math.round(newValueAsNum * roundingMultiplier) / roundingMultiplier;
//only write if it changed
if (valueToWrite !== current) {
target(valueToWrite);
} else {
//if the rounded value is the same, but a different value was written, force a notification for the current field
if (newValue !== current) {
target.notifySubscribers(valueToWrite);
}
}
}
}).extend({ notify: 'always' });
//initialize with current value to make sure it is rounded appropriately
result(target());
//return the new computed observable
return result;
};
function AppViewModel(one, two) {
this.myNumberOne = ko.observable(one).extend({ numeric: 0 });
this.myNumberTwo = ko.observable(two).extend({ numeric: 2 });
}
ko.applyBindings(new AppViewModel(221.2234, 123.4525));
I had a similar problem.
I also needed to ensure inter values only, and for IE9 and up (so type=numberical was not enough), and since we have a lot of international customers, i could not rely on keycodes either, so the following is what i ended up with:
//In my js class method (self is this as usual)
self.ensureNumberical = function (data, e) {
var keyValue = e.key;
if (keyValue.match(/[0-9]/g)) {
return true;
}
return false;
}
//In my MVC View
data-bind="event: { keypress: ensureNumberical }"
An alternative approach: I have found that Knockout works well in combination with jQuery-validate. You just need to make sure that you validate the form before you attempt to use the numeric value.
Say you have a form DOM element, you can set up validation rules via
$(".yourform").validate({
rules: {
year: {
digits: true,
minlength: 4,
maxlength: 4
}
},
messages: {
year: "Please enter four digits (e.g. 2009).",
}
});
In your viewmodel you set the two-way binding up as usual, e.g. via self.year = ko.observable(""). Now make sure that you call $(".yourform").valid() before you are further processing self.year(). In my case, I am doing var year = parseInt(self.year(), 10). Right after form validation this is expected to always produce a meaningful result.
Best for today's scenerio https://github.com/Knockout-Contrib/Knockout-Validation
run the snippet below. entering a non digit or something more than 255 will cause the message to display.
function model() {
var self = this;
this.myObj = ko.observable().extend({ digit: true }).extend({ max: 255});
}
var mymodel = new model();
$(document).ready(function() {
ko.validation.init();
ko.applyBindings(mymodel);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.3/knockout.validation.min.js"></script>
enter a digit less than or equal to 255 <input type="text" data-bind="textInput: myObj">
<p>
Enter something other than a digit or over 255 will cause an error.
</p>
courtesy: Bryan Dellinger: https://stackoverflow.com/a/42940109/3868653
<input type="text" id="alpha-validation" data-bind="value: YourDataName, valueUpdate: 'afterkeydown' , event: { 'input': AlphaCheck}" style="text-transform:uppercase">
create AlphaCheck Function and add that.
$('#alpha-validation').keyup(function () {
if (this.value.match(/[^0-9 ]/g)) {
this.value = this.value.replace(/[^0-9 ]/g, '');
}
});
That will works!
We can restrict user to input user more than two decimal number Ex. 23.81, 3452.83 Modified code is as below. The reference code is taken from the #Martin Surynek answer.
HTML -
<p>
<input data-bind="value: myNumberOne" /> (round to whole number)</p>
<p>
<input data-bind="num, value: myNumberTwo" /> (round to two decimals)</p>
Script -
<script>
ko.bindingHandlers.num = {
init: function (element, valueAccessor) {
$(element).on("keypress", function (event) {
//debugger
console.log(event.keyCode);
var $this = $(this);
var text = $this.val();
// Stop insert two dots
if ($this.val().indexOf('.') != -1 && (event.which == 190 || event.which == 110)) {
event.preventDefault();
}
// Allow: backspace, delete, tab, escape, and enter
if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode ==
13 ||
// Allow: Ctrl+A
(event.keyCode == 65 && event.ctrlKey === true) ||
// Allow: . ,event.keyCode == 188 ||
( event.keyCode == 190 || event.keyCode == 110) ||
// Allow: home, end, left, right
(event.keyCode >= 35 && event.keyCode <= 39)) {
// let it happen, don't do anything
return;
}
// Ensure that it is a number and stop the keypress
if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode >
105)) {
event.preventDefault();
}
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();
}
//console.log($(this)[0].selectionStart >= text.length - 2);
});
}
};
ko.extenders.numeric = function (target, precision) {
//create a writable computed observable to intercept writes to our observable
var result = ko.pureComputed({
read: target, //always return the original observables value
write: function (newValue) {
var current = target(),
roundingMultiplier = Math.pow(10, precision),
newValueAsNum = isNaN(newValue) ? 0 : parseFloat(+newValue),
valueToWrite = Math.round(newValueAsNum * roundingMultiplier) / roundingMultiplier;
//only write if it changed
if (valueToWrite !== current) {
target(valueToWrite);
} else {
//if the rounded value is the same, but a different value was written, force a notification for the current field
if (newValue !== current) {
target.notifySubscribers(valueToWrite);
}
}
}
}).extend({
notify: 'always'
});
//initialize with current value to make sure it is rounded appropriately
result(target());
//return the new computed observable
return result;
};
function AppViewModel(one, two) {
this.myNumberOne = ko.observable(one).extend({
numeric: 0
});
this.myNumberTwo = ko.observable(two).extend({
numeric: 2
});
}
ko.applyBindings(new AppViewModel(221.2234, 123.4525));
</script>
I know this question is a year old but let me post this for the sake of feature visitor of the page.
Check this out:
ko.bindingHandlers.numericnumbers = {
init: function (element) {
$(element).on('keypress', function (number) {
number = (number) ? number : window.event;
var charcode = (number.which) ? number.which : number.keyCode;
if (charcode > 31 && (charcode < 48 || charcode > 75))
number.preventDefault();
});
}};
Create you data-bind pointing at your shiny new code:
<input id="price" name="price" type="text" data-bind="numeric">
Shiny new knockout code:
price = ko.observable();
price.subscribe(function(newValue) {
price = newValue.replace(/[\D\.]/g, '');
});
This means that every time you update the price, it will apply the logic in the function (in this case stripping out anything that isn't a number or a period), and apply it directly to the price. You can also add other validation or cool features here, like adding a currency sybmol at the start, keeping it to 2 decimal places, etc...
With the help of "keydown" event we can restrict other key's in text box which should hold numeric values.
$(document).ready(function(){
$("selector").on("keydown", function (e) {
//numbers, delete, backspace, arrows
var validKeyCodes = [8, 9, 37, 38, 39, 40, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57];
if (!($.inArray(e.keyCode, validKeyCodes) >= 0))
e.preventDefault();
});
});

How to restrict a field to take only 4 numeric characters as input?

I wanted a text field to take only numbers ans some control keys and number should be exactly four digit long, not less not more. My validation code is
function checkValidInput()
{
$(".validateYearTextBox").keydown(function(event)
{
// Allow only delete, backspace,left arrow,right arraow and Tab
if (
event.keyCode == 46 //delete
|| event.keyCode == 8 //backspace
|| event.keyCode == 37 //leftarow
|| event.keyCode == 39 //rightarrow
|| event.keyCode == 9 //tab
)
{
// 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.keyCode <96 ||event.keyCode > 105) ) {
event.preventDefault();
}
}
});
$(".validateYearTextBox").keyup(function(event)
{
var val = $(this).val();
if (val.length > 4){
alert ("Max length is 4");
val = val.substring(0, valore.length - 1);
$(this).val(val);
$(this).focus();
return false;
}
});
}
Here, my first validation is working, but my send one is not working.
I am calling this validation function in my aspx page like this
<script type="text/javascript">
$(document).ready(function(){
checkValidInput();
}
</script>
What is going wrong?
Simplify it:
function checkValidInput() {
// Allow only delete, backspace, left arrow, right arrow,
// Tab, ctrl+v and numbers
$(".validateYearTextBox").keydown(function(event) {
if (!((event.keyCode == 46 ||
event.keyCode == 8 ||
event.keyCode == 37 ||
event.keyCode == 39 ||
event.keyCode == 9) ||
(event.ctrlKey && event.keyCode == 86) || // Edit: Added to allow ctrl+v
$(this).val().length < 4 &&
((event.keyCode >= 48 && event.keyCode <= 57) ||
(event.keyCode >= 96 && event.keyCode <= 105)))) {
// Stop the event
event.preventDefault();
return false;
}
});
// Edit: Added validate after copy+paste.
// This removes non-numeric characters and truncates the length
// to 4 if the user copy + pasted.
$(".validateYearTextBox").change(function(event) {
var value = $(this).val();
value = value.replace(/[^0-9]/g,'');
value = value.substr(0,4);
$(this).val(value);
});
}
$(document).ready(function() {
checkValidInput();
});
http://jsfiddle.net/nwellcome/687kD/
Edit: Personally I like the Masked Input jQuery plugin but that might be a heavy-handed solution if this is all you need to do.
There are many, many jQuery plugins that already do this in one form or another.
One that does mostly1 what you want is Masked Input Plugin. If you can, I recommend using something existing, working and proven, rather than reinventing.
1 The only part that it doesn't seem to do is display an error if a user tries to enter more than n characters but I'm sure you could modify the plugin or add a length check to the <input>
Use regular expression :
enter code here
function validator(elem,msg)
{
var exp=/^([0-9]+)$/; //it only allows for numbers
if(elem.value.match(exp))
{return true;}
else
{
alert(msg);
elem.focus();
return false;
}
}
the html code :
enter code here
<html><head>
<script src="javasript.js" type="text/javascript">
</head>
<body>
<form method=POST>
<input type='text' maxlength=4 name='num' id='num'>
<input type='submit' value=OK onClick="validator(document.getElementById('num'),'Only four numbers and numbers only!');">
</form> //the maxlength in input text tag restrict the maximum length of the input
</body></html>
Here's a simple way of doing it. Stores the old text before an event changes the text. Then check to see if the new text is valid or not. If it isn't, then revert back to the old text. To further ensure the maximum of 4 characters, add a maxlength attribute to all <input type="text"> elements.
jQuery.fn.forceNumericOnly = function() {
return this.each(function() {
var oldText;
$(this).keyup(function(e) {
var newText = $(this).val();
if (newText != "" && (isNaN(newText) || val.length > 4))
$(this).val(oldText);
else
oldText = $(this).val();
})
$(this).blur(function(e) {
var newText = $(this).val();
if (newText != "" && (isNaN(newText) || val.length > 4))
$(this).val(newText = oldText);
else
oldText = $(this).val();
});
})
};
$(".validateYearTextBox").forceNumericOnly();
if (document.ExamEntry.examnum.value=="") {
msg+="You must enter your examination number \n";
document.ExamEntry.examnum.focus();
document.getElementById('examnum').style.color="red";
result = false;
}
$('.numeric').keypress(function(e) {
var verified = (e.which == 8 || e.which == undefined || e.which == 0) ? null : String.fromCharCode(e.which).match(/[^0-9]/);
if (verified || e.delegateTarget.value.length>3 || e.ctrlKey ==true) { if(e.which!=8 ){e.preventDefault();}}
}).on('paste',function(e){ e.preventDefault();});
Here add class=numeric to input text box'. it will allow only 4 digits if you want to limit size to 2 digits change to e.delegateTarget.value.length>1 and so on as index starts from zero
Use HTML input maxlength attribute for this and also set the size value of fixing width 4 in same input size attribute.
<input type="text" maxlength="4" size="4">
Here is a simple answer that takes care of copy paste and all.
$(document).on("input", ".validateYearTextBox", function() {
var value = this.value
value = value.replace(/\D/g,'');
for (i = 0; i < value.length; i++) {
if (i > 3) {
value = value.replace(value[i], '')
}
}
});

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