The commas are getting added correctly, but I'm getting this error message in the console:
"The specified value "NaN" is not a valid number"
I tried by making it as type="number", still the same warning.
jQuery(function() {
var extra = 0;
var $input = jQuery(".total_crm_records");
$input.on("keyup", function(event) {
// When user select text in the document, also abort.
var selection = window.getSelection().toString();
if (selection !== '') {
return;
}
// When the arrow keys are pressed, abort.
if ($.inArray(event.keyCode, [38, 40, 37, 39]) !== -1) {
if (event.keyCode == 38) {
extra = 1000;
} else if (event.keyCode == 40) {
extra = -1000;
} else {
return;
}
}
var $this = jQuery(this);
// Get the value.
var input = $this.val();
var input = input.replace(/[\D\s\._\-]+/g, "");
input = input ? parseInt(input, 10) : 0;
input += extra;
extra = 0;
$this.val(function() {
return (input === 0) ? "" : input.toLocaleString("en-US");
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
Input field : <input type="text" data-type="number" maxlength="20" class="total_crm_records">
Related
I am trying to validate user input in a text input field.
I have written a javascript function for the same purpose which fires on onkeyup event.
The goal is to only allow user input if it's a numeric value less than 100 and with at most 1 decimal place.
The function is working fine but if a enter an invalid character ,say 'a', it will flash in the input box before being removed.
What I want is that if the entered character violates the defined condition it should not appear in the input box (as it is flashing right now for a split second).
Here's my code:
function validatePercent(event) {
var txt = $("#tds_input").val();
// alert(event.source);
if (!parseInt(txt)) {
$("#tds_input").val('');
}
if (isNaN(txt / 1)) {
txt = txt.substr(0, txt.length - 1);
$("#tds_input").val(txt);
}
if (txt > 100) {
//alert(2);
txt = txt.toString();
txt = txt.substr(0, txt.length - 1);
$("#tds_input").val(txt);
}
txt = txt.toString();
if (txt.indexOf('.') > -1) {
if (txt.substr(txt.indexOf('.') + 1, txt.length).length > 1) {
txt = txt.substr(0, txt.length - 1);
$("#tds_input").val(txt);
}
}
}
Using type=number (and not text) can help
function validatePercent(event)
{
var txt=$("#tds_input").val();
if(!parseInt(txt))
{
$("#tds_input").val('');
}
if(isNaN(txt/1))
{
txt=txt.substr(0,txt.length-1);
$("#tds_input").val(txt);
}
if(txt>100)
{
txt=txt.toString();
txt=txt.substr(0,txt.length-1);
$("#tds_input").val(txt);
}
txt=txt.toString();
if(txt.indexOf('.')>-1)
{
if(txt.substr(txt.indexOf('.')+1,txt.length).length>1){
txt=txt.substr(0,txt.length-1);
$("#tds_input").val(txt);
}
}
}
input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id = "tds_input" onkeyup="validatePercent()">
UPDATED
You could store the value of the when the focus is in the input.
When the user enters a valid percentage (integer only), replace the value stored. When inputs is incorrect, just replace with the old value.
var decimalSeparator = 1.1.toLocaleString().replace(/\d/g, ''),
pattern1 = "^(\\d{1,3})?([",
pattern2 = "]?\\d{1})?$",
regex = new RegExp(pattern1+decimalSeparator+pattern2),
resetContent = function () {
$('#tds_input').val($('#tds_input').data('val'));
},
matchRegex = function (value) {
return value.match(regex);
};
$('#tds_input').bind('focusin', (e) => {
$('#tds_input').data('val', $('#tds_input').val());
});
// handle input (keys, paste)
$('#tds_input').bind('input', (e) => {
let txtValue = $('#tds_input').val();
// input is empty
if (txtValue === "") {
$('#tds_input').data('val', "");
return;
}
// value does not match regex
if (!matchRegex(txtValue)) {
// maybe it ends with the decimal character?
if (txtValue[txtValue.length - 1] === "." && txtValue !== "100.") {
// simulate the user enters a decimal next
if (matchRegex(txtValue + "1")) {
$('#tds_input').data('val', txtValue);
return;
}
}
resetContent();
return;
}
// check between 0 and 100
let value = parseFloat(txtValue);
if (value >= 0 && value <= 100) {
// store new valid number
$('#tds_input').data('val', value);
// put the value as an integer in the input
$('#tds_input').val(value);
return;
} else resetContent();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="tds_input"/>
I have a situation having a textbox having 15 as a max length property. That field works as a amount field. it is working correctly in normal cases.
lets say if i enter 11234567890.99 this amount in textbox it displays it as 112,34,567,890.99 which is expected.
But, if i copy & paste 112,34,567,890.99 amount in textbox last two digits gets truncated because the length gets out of bound.
Is there any ways to change this without modifying the exact behavior? allowing to paste whole 112,34,567,890.99 amount.
$(document).on("focusout","#txtformate1",(function () {
if (this.value != null && this.value != "") {
$((this.parentElement).nextElementSibling).hide()
}
else{
$((this.parentElement).nextElementSibling).show()
}
}));
$(document).on('keyup', '.Amt', function () {
var val = $(this).val();
val = val.replace(/([~!#$%^&*()_+=`{}\[\]\|\\:;'<>,\/? ])+/g, '');
if(isNaN(val) && val!="-")
{
val="";
}
$(this).val(val);
/*if (isNaN(val)) {
val = val.replace(/(?!^)-/g, '');
if(val.indexOf("-")>-1)
{
val = val.replace(/[`*\/]/g, '');
}
else{val = val.replace(/[^0-9\.]/g, '');}
if (val.split('.').length > 2)
{
val = val.replace(/\.+$/, "");
}
else if(val==".")
{
val ="";
}
}*/
});
$(document).on('focusout', '.Amt', function () {
var val = $(this).val();
val = val.replace(/(?!^)-/g, '');
if(isNaN(val) && val.indexOf(',')>-1){
val=$(this).val();
}
if (val == "0.00"){
val="";
}
$(this).val(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control Amt" id="txtformate1" maxlength="15" />`
i want to add thousand separator on keyup event in input type number
but this work just in 6 character, if more than 6 character, value on input has reseted
this my short code
<input type="number" id="tanpa-rupiah" step="any">
var dengan_rupiah = document.getElementById('dengan-rupiah');
dengan_rupiah.addEventListener('keyup', function(e)
{
dengan_rupiah.value = formatRupiah(this.value, 'Rp. ');
});
function formatRupiah(bilangan, prefix)
{
var number_string = bilangan.replace(/[^,\d]/g, '').toString(),
split = number_string.split(','),
sisa = split[0].length % 3,
rupiah = split[0].substr(0, sisa),
ribuan = split[0].substr(sisa).match(/\d{1,3}/gi);
if (ribuan) {
separator = sisa ? '.' : '';
rupiah += separator + ribuan.join('.');
}
rupiah = split[1] != undefined ? rupiah + ',' + split[1] : rupiah;
return prefix == undefined ? rupiah : (rupiah ? 'Rp. ' + rupiah : '');
}
this my fiddle https://jsfiddle.net/C2heg/4619/
This might suit you. On keydown prevent the default action if it is not a number key. On keyup, parse the value and update it. Use the data- attributes to store and get the original value.
var elem = document.getElementById("num");
elem.addEventListener("keydown",function(event){
var key = event.which;
if((key<48 || key>57) && key != 8) event.preventDefault();
});
elem.addEventListener("keyup",function(event){
var value = this.value.replace(/,/g,"");
this.dataset.currentValue=parseInt(value);
var caret = value.length-1;
while((caret-3)>-1)
{
caret -= 3;
value = value.split('');
value.splice(caret+1,0,",");
value = value.join('');
}
this.value = value;
});
function showValue()
{
console.log(document.getElementById("num").dataset.currentValue);
}
<input type="text" id="num" maxlength="30">
<button onclick="showValue()">Get Value</button>
Ok I have posted answer below. I have added limit of 20 numbers. You can change it as per your need.
You can use Number.toLocaleString() for this purpose.
Below is working example:
// When ready.
$(function() {
var extra = 0;
var $input = $("#amount");
$input.on("keyup", function(event) {
// When user select text in the document, also abort.
var selection = window.getSelection().toString();
if (selection !== '') {
return;
}
// When the arrow keys are pressed, abort.
if ($.inArray(event.keyCode, [38, 40, 37, 39]) !== -1) {
if (event.keyCode == 38) {
extra = 1000;
} else if (event.keyCode == 40) {
extra = -1000;
} else {
return;
}
}
var $this = $(this);
// Get the value.
var input = $this.val();
var input = input.replace(/[\D\s\._\-]+/g, "");
input = input ? parseInt(input, 10) : 0;
input += extra;
extra = 0;
$this.val(function() {
return (input === 0) ? "" : input.toLocaleString("en-US");
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="amount" name="amount" type="text" maxlength="20" />
change your the input type equal to "text" then its work
<input type="text" id="tanpa-rupiah" step="any">
checkout jsfiddle
I have one textbox.It should be allow only decimal numbers and after dot only allow two digit(example 34545.43). how we can do it using jquery i have searched in google and stackoverflow but not satisfied answer because some script is not working in chrome and firefox. I tried but it is not working properly.So need help how to do it.http://jsfiddle.net/S9G8C/1685/
Js:
$('.allow_decimal').keyup(function (evt) {
var self = $(this);
self.val(self.val().replace(/[^0-9\.]/g, ''));
if ((evt.which != 46 || self.val().indexOf('.') != -1) && (evt.which < 48 || evt.which > 57)) {
evt.preventDefault();
}
});
This jQuery function will round the value on blur event of textbox
$.fn.getNum = function() {
var val = $.trim($(this).val());
if(val.indexOf(',') > -1) {
val = val.replace(',', '.');
}
var num = parseFloat(val);
var num = num.toFixed(2);
if(isNaN(num)) {
num = '';
}
return num;
}
$(function() { //This function will work on onblur event
$('#txt').blur(function() {
$(this).val($(this).getNum());
});
});
Number: <input type="text" id="txt" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can directly remove the 3rd digit when the user enters that.
var txt = document.getElementById('txtId');
txt.addEventListener('keyup', myFunc);
function myFunc(e) {
var val = this.value;
var re = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)$/g;
var re1 = /^([0-9]+[\.]?[0-9]?[0-9]?|[0-9]+)/g;
if (re.test(val)) {
//do something here
} else {
val = re1.exec(val);
if (val) {
this.value = val[0];
} else {
this.value = "";
}
}
}
<input id="txtId" type="text"></input>
I have a text box, I want to get the deleted character when I press a backspace or delete key.
I have a key up event handler and i am capturing if the key is backspace. Now inside this I need to perform some tasks based on the key deleted. Please help.
After making a little tweak for the getCursorPosition function in this thread, you can get the characters deleted by tracking the current cursor selection.
The code handles the following conditions:
Type and then backspace at the end.
Move cursor in the middle of the text and delete/backspace.
Select a piece of text and then delete/backspace.
$.fn.getCursorPosition = function() {
var el = $(this).get(0);
var pos = 0;
var posEnd = 0;
if('selectionStart' in el) {
pos = el.selectionStart;
posEnd = el.selectionEnd;
} else if('selection' in document) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
posEnd = Sel.text.length;
}
// return both selection start and end;
return [pos, posEnd];
};
$('#text').keydown(function (e) {
var position = $(this).getCursorPosition();
var deleted = '';
var val = $(this).val();
if (e.which == 8) {
if (position[0] == position[1]) {
if (position[0] == 0)
deleted = '';
else
deleted = val.substr(position[0] - 1, 1);
}
else {
deleted = val.substring(position[0], position[1]);
}
}
else if (e.which == 46) {
var val = $(this).val();
if (position[0] == position[1]) {
if (position[0] === val.length)
deleted = '';
else
deleted = val.substr(position[0], 1);
}
else {
deleted = val.substring(position[0], position[1]);
}
}
// Now you can test the deleted character(s) here
});
And here is Live Demo
You could use the keydown event handler instead so that the last character to be deleted is still available:
$('textarea').on('keydown',function(e) {
var deleteKeyCode = 8,
value = $(this).val(),
length = value.length,
lastChar = value.substring(length-1, length);
if (e.which === deleteKeyCode) {
alert(lastChar);
}
});
Live Demo
$('input').keydown(function(e){
$(this).data('prevVal', $(this).val());
}).keyup(function(e){
if(e.keyCode === 8) {//delete
var ele = $(this);
var val = ele.data('prevVal');
var newVal = ele.val();
var removedChar = val.substring(val.length-1);
alert(removedChar);
}
});