Restrict to 2 decimal places in keypress of a text box? - javascript

I want to enter a decimal point in a text box. I want to restrict the user by entering more than 2 digits after the decimal point. I have written the code for achieving that in the Keypress event.
function validateFloatKeyPress(el, evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
if (charCode == 46 && el.value.indexOf(".") !== -1) {
return false;
}
if (el.value.indexOf(".") !== -1)
{
var range = document.selection.createRange();
if (range.text != ""){
}
else
{
var number = el.value.split('.');
if (number.length == 2 && number[1].length > 1)
return false;
}
}
return true;
}
<asp:TextBox ID="txtTeamSizeCount" runat="server" onkeypress="return validateFloatKeyPress(this,event);" Width="100px" MaxLength="6"></asp:TextBox>
The code is working but the issue is: if I enter ".75" and then change it to "1.75", it is not possible. Only way to do it is delete it completely and then type "1.75". This issue occurs if there are already 2 digits after decimal in the textbox. The conditions that I impose are
a) After decimal is present, it must at least have 1 or 2 digits. For ex .75 or .7 or 10.75 or 333.55 or 333.2 is accepted. but not .753 or 12.3335
b) Before the decimal, it not a must for the user to enter a value. User must also be able to enter integer numbers also.
Can you tell me what could be the issue?
Thanks,
Jollyguy

You were almost there. Just check that there are no more than 2 characters after the decimal.
UPDATE 1 - check carat position to allow character insertion before the decimal.
UPDATE 2 - correct issue pointed out by ddlab's comment and only allow one dot.
function validateFloatKeyPress(el, evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
var number = el.value.split('.');
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
//just one dot (thanks ddlab)
if(number.length>1 && charCode == 46){
return false;
}
//get the carat position
var caratPos = getSelectionStart(el);
var dotPos = el.value.indexOf(".");
if( caratPos > dotPos && dotPos>-1 && (number[1].length > 1)){
return false;
}
return true;
}
//thanks: http://javascript.nwbox.com/cursor_position/
function getSelectionStart(o) {
if (o.createTextRange) {
var r = document.selection.createRange().duplicate()
r.moveEnd('character', o.value.length)
if (r.text == '') return o.value.length
return o.value.lastIndexOf(r.text)
} else return o.selectionStart
}
http://jsfiddle.net/S9G8C/1/
http://jsfiddle.net/S9G8C/203/

Consider leveraging HTML5's Constraint Validation API. It doesn't necessarily prevent typing invalid values, but the field is marked invalid and it halts submission of the <form> (by default). I added the <output> to illustrate why the browser considers e.g. "1.100" a valid value (it sees the numeric value as "1.1").
<input id="n" type="number" step=".01">
var
n = document.getElementById('n'),
o = document.getElementById('o'),
didInputN = function(e) {
o.value = n.valueAsNumber;
};
n.addEventListener('input', didInputN);
input:invalid {
color: white;
background-color: red;
}
<input id="n" type="number" step=".01">
<output id="o" for="n"></output>
Philosophically, you might consider this a more usable approach as it allows the user to paste an invalid entry and edit it directly in the field.

You can do it by another way with onchange event, to not restrict to user to type, rather just convert number after typing, to make uniform, like this,
function validateFloatKeyPress(el) {
var v = parseFloat(el.value);
el.value = (isNaN(v)) ? '' : v.toFixed(2);
}
<input id="aninput" type="text" onchange="validateFloatKeyPress(this);" />
45.846 should be 45.85 but in your code user needed to convert their-self and then they will type 45.85 directly

1.)No multiple decimals points.
2.)Two numbers after decimal point.
3.)Allow only Numbers and one decimal point(.).
This will help.jsFiddle

function decimalValidation(el, evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
var number = el.value.split('.');
if(charCode == 8) {
return true;
}
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
//just one dot
if(number.length>1 && charCode == 46){
return false;
}
//get the carat position
var caratPos = getSelectionStart(el);
var dotPos = el.value.indexOf(".");
if( caratPos > dotPos && dotPos>-1 && (number[1].length > 1)){
return false;
}
return true;
}
function getSelectionStart(o) {
return o.selectionStart
}
Hi #webvitaly The above code will work in IE too please check
And backspace after decimals not working in Mozilla i updated my answer.

this code is very complet, I change "." to ",":
can't "," in begin
can't write more ","
<script type="text/javascript">
function isNumberKey(evt, el) {
var charCode = (evt.which) ? evt.which : event.keyCode;
var number = el.value.split(',');
var caracter = el.value;
if (charCode != 44 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
if (charCode == 44 && caracter == "") {
return false;
}
if (charCode == 44 && caracter.indexOf(",") != -1) {
return false;
}
//get the carat position
var caratPos = getSelectionStart(el);
var dotPos = el.value.indexOf(",");
if (caratPos > dotPos && dotPos > -1 && (number[1].length > 1)) {
return false;
}
return true;
}
function getSelectionStart(o) {
if (o.createTextRange) {
var r = document.selection.createRange().duplicate()
r.moveEnd('character', o.value.length)
if (r.text == '') return o.value.length
return o.value.lastIndexOf(r.text)
} else return o.selectionStart
}
</script>

My problem was that I need it to show an error message in real time if the user is allowed only 2 decimals:
value = parseFloat(valueFromInput);
parseFloat(value.toFixed(2)) !== value // condition to check
The above code worked for me..toFixed converts the float to a string wit only 2 decimals and I have to convert back to float to check with the initial value if are the same.
P.S. And before this condition you should check if the value is NaN.

Related

How could I set a maxlength to an HTML "td" tag (cell)?

I have a HTML table with editable cells (every td tag in my table has "contenteditable" set to True).
The users are meant to fill the table with times in HH:mm format, so I added an onkeypress attribute which triggers a function that checks if the user is entering something other than numbers or the ":" character, and ignores it if that's the case, like so:
HTML
<td contenteditable="true" onkeypress="return isNumberKey(event)"> </td>
Javascript
function isNumberKey(evt){
let charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode!=58)
return false;
return true;
}
The problem now is that users can enter more that 5 characters and write stuff like "345:678" for example.
I would like to know if its possible to limit the number of characters they can enter in the cell to 5 (just like an input tag's "maxlength" attribute), and if it's possible to somehow limit the users to typing two numbers, then a ":" character, then two more numbers. (Even though setting a maxlength would already be pretty nice).
I also wrote a Regex which checks that something is the HH:mm format, but I don't think it's useful in this case since it can only be tested after the user has typed the full five characters, right?
Here it is just in case:
const timeRegex = RegExp("^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$");
Here is the JSFiddle
if you already do the checking which characters a user can input into the td with javascript, so why don't just also add the functionality for the current length and other characters to the function too ?
F.e. like this:
function isNumberKey(evt){
let charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode!=58)
return false;
var currentContent = evt.target.innerHTML;
if (currentContent.length >= 5)
return false;
if (currentContent.length === 2 && charCode !== 58)
return false;
return true;
}
I'm accepting #Ekk4rd 's answer because he really put me on the right track but I still wanted to post an answer with the finished code that matches exactly what I asked in the question. Here it is:
HTML
<td contenteditable="true" onkeypress="return isNumberKey(event)"> </td>
Javascript
function isNumberKey(evt){
let charCode = (evt.which) ? evt.which : event.keyCode;
console.log(evt.target.innerHTML);
if (evt.target.innerHTML == "<br>" || evt.target.innerHTML == " <br>"){
evt.target.innerHTML = "";
}
let currentContent = evt.target.innerHTML;
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode!=58){
return false;
}
if (currentContent.length >= 5){
return false;
}
if (currentContent.length === 2 && charCode !== 58){
return false;
}
if (currentContent.length != 2 && charCode == 58){
return false;
}
return true;
}
Here is the JSFiddle

restrict user to input only two digit after decimal

I want user to restrict user that they can only enter two digit after decimal.
but they can also remove the entered digits using space key. I have following code but its not allowing me to remove the entered digits using space Like:
Suppose I have entered : 5454645.54 now if user will move cursoe on text box and want to remove these digits its not allowing user to do so. Please advice which correction need to do for this in following code:
function restrictUser(el, evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
var number = el.value.split('.');
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
if(number.length>1 && charCode == 46){
return false;
}
var caratPos = getSelectionStart(el);
var dotPos = el.value.indexOf(".");
if( caratPos > dotPos && dotPos>-1 && (number[1].length > 1)){
return false;
}
return true;
}
function getSelectionStart(o) {
if (o.createTextRange) {
var r = document.selection.createRange().duplicate()
r.moveEnd('character', o.value.length)
if (r.text == '') return o.value.length
return o.value.lastIndexOf(r.text)
} else return o.selectionStart
}
Thanks Advance.

asp textbox javascript validator

there are many post about how to prevent an ASP textbox to accept only numbers, but could somebody give me a JS example, how to check if the entered value is between 0-100?
My validator fires each time key is entered and checks if it is a number or not, but do not know how to extend it to check the final value against 0-100 range.
function onlyDotsAndNumbers(event) {
var charCode = (event.which) ? event.which : event.keyCode
if (charCode == 46) {
return true;
}
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
Cheers
A
You need to check out the whole value of the text box.
function onlyDotsAndNumbers(event) {
var charCode = (event.which) ? event.which : event.keyCode
if (charCode == 46) {
return true;
}
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
var boxValue = $(event.target).val();
if (boxValue > 100 || boxValue < 0)
return false;
return true;
}

allowing input only for float number

I have pain-time when making input that only allows float number with jquery library. my code can't prevent chacacter "." when it's becoming first input, can anyone guide me to solve this problem?
$('.filterme').keypress(function(eve) {
if ( ( eve.which != 46 || $(this).val().indexOf('.') != -1 )
&& ( eve.which < 48 || eve.which > 57 )
|| ( $(this).val().indexOf('.') == 0)
)
{
eve.preventDefault();
}
});​
I use this - works for keyboard input or copy and paste
$('input.float').on('input', function() {
this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<input type="text" class="float" />
Explanation:
First regex replaces anything that's not a number or a decimal.
Second regex removes any instance of a second decimal.
I filter the first position input with the jQuery Caret plugin. Otherwise, once the dot is typed, it's already late to check where it was placed. I tried checking for the dot, then deleting the dot, but it does not look nice.
jQuery caret plugin:
http://examplet.buss.hk/js/jquery.caret.min.js
What I did:
http://jsfiddle.net/FCWrE/422/
Try it :)
$('.filterme').keypress(function(eve) {
if ((eve.which != 46 || $(this).val().indexOf('.') != -1) && (eve.which < 48 || eve.which > 57) || (eve.which == 46 && $(this).caret().start == 0)) {
eve.preventDefault();
}
// this part is when left part of number is deleted and leaves a . in the leftmost position. For example, 33.25, then 33 is deleted
$('.filterme').keyup(function(eve) {
if ($(this).val().indexOf('.') == 0) {
$(this).val($(this).val().substring(1));
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/caret/1.0.0/jquery.caret.min.js"></script>
<input type="text" class="filterme">
Regular expression would be my recommendation as well. If the value is being passed as a number and not a string you can use .toString to change it to a string and validate it with regular expression. For example:
var str = value.toString();
if(!str.match(/^-?[0-9]*[.][0-9]+$/)) {
alert("Value must be a float number");
return;
}
return value;
The above regex will match if the value passed is a floating point number. It accepts both negative and positive numbers. If you only want to accept positive numbers simply remove the '-?' from the expression. It will also fail if the value is simply zero '0' without any decimal point. If you want to accept zero simply add it as a condition to the 'if' statement.
You can use the above validation and an onchange event to prevent the user from entering a non-flot number.
Why not using Regular Expression
^[0-9]*[.][0-9]+$
Read code and test here..
You can use the following method, called on onkeypress event. Below is the HTML snippet followed by the JS method:
input type="text" onkeypress="return isNumberKey(event)" id="floor"
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode == 46){
var inputValue = $("#floor").val();
var count = (inputValue.match(/'.'/g) || []).length;
if(count<1){
if (inputValue.indexOf('.') < 1){
return true;
}
return false;
}else{
return false;
}
}
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)){
return false;
}
return true;
}
Note: The above code also ensures that you enter only single decimal in the input.
Here is my solution, works with negative numbers too (fiddle)
$("input").keypress(function (event) {
var inputCode = event.which;
var currentValue = $(this).val();
if (inputCode > 0 && (inputCode < 48 || inputCode > 57)) {
if (inputCode == 46) {
if (getCursorPosition(this) == 0 && currentValue.charAt(0) == '-') return false;
if (currentValue.match(/[.]/)) return false;
}
else if (inputCode == 45) {
if (currentValue.charAt(0) == '-') return false;
if (getCursorPosition(this) != 0) return false;
}
else if (inputCode == 8) return true;
else return false;
}
else if (inputCode > 0 && (inputCode >= 48 && inputCode <= 57)) {
if (currentValue.charAt(0) == '-' && getCursorPosition(this) == 0) return false;
}
});
function getCursorPosition(element) {
if (element.selectionStart) return element.selectionStart;
else if (document.selection)
{
element.focus();
var r = document.selection.createRange();
if (r == null) return 0;
var re = element.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
}
This works for me:
var str = document.getElementById('product_'+id_product).value;
if( !str.match(/^[0-9]*([.,][0-9]+)?$/) ) {
console.log("Value must be a number or float number");
}else{
console.log("The number is valid");
}
I hope this can help someone.
Regards!

Javascript event keypress check for Char Code

Statement: I have a input field.User enters only Numbers in it. Max allowed value is 500.
So if user tries to type a value greater than 500 he should not be able to type the value.
For example:
Hundreds place max value would be 5 if user tries to enter 600 or 700.
Tens and Units place Max value would be 0 if user has typed 5 as the first digit(hundreds place)
PS : The handling for user entering only numbers is done already using the following code snippet:
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
};
Fix for the Problem:
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
if(!(charCode > 31 && (charCode < 48 || charCode > 57)) && charCode != 8){
if($(evt.currentTarget).value.length == 3){
return false;
}
if($(evt.currentTarget).value.length == 2){
if($(evt.currentTarget).value.substring(0,1) > 5){
return false;
}else if($(evt.currentTarget).value.substring(0,1) == 5 && $(evt.currentTarget).value.substring(1,2) > 0 ){
return false;
}
}
}
return true;
};
As i understand you can use onchange instead of keypress:
$('#textbox').change( function(){
elem = $(this);
if(parseInt(elem.val()) > 500)
elem.val('500');
});

Categories

Resources