This is simplified of my code:
$("#annual_sales").on('keyup', function () {
$(this).val( $(this).val().replace(/(\d{3})/g, "$1,") );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="annual_sales" type="text" />
I'm trying to add a comma after every 3 digits.
The patterns works well here, but as you can see (in the code snippet above) it doesn't work in the JS. Any idea what's wrong?
Presumably, you want these commas added from the right as a US-style number separator. This code will do that by reversing before and after adding the commas.
var addCommas = s => s.split('').reverse().join('')
.replace(/(\d{3})/g, '$1,').replace(/\,$/, '')
.split('').reverse().join('') // Really want String.prototype.revese!
$("#annual_sales").on('keyup', function () {
$(this).val( addCommas($(this).val().replace(/\,/g, '')) );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="annual_sales" type="text" />
(Doing the reverses by converting to an array really makes me want a String.prototype.reverse method.)
If you have to support numbers with more than two decimal places, there would have to be additional work on this function.
Doesn't work here since the event fire multiple time, then you need to remove the previous added comma's first every time the event fired and add new ones in the desired positions :
$(this).val().replace(/,/g,'').replace(/(\d{3})/g, "$1,")
** NOTE:** I suggest the use of input event instead since it's more efficient when tracking the use inputs, also you could adjust the regex so the comma will not be added at the end of the line :
/(\d{3}(?!$))/g
$("#annual_sales").on('input', function() {
$(this).val($(this).val().replace(/,/g, '').replace(/(\d{3}(?!$))/g, "$1,"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="annual_sales" type="text" />
In your current pattern (\d{3}) you add a comma after matching 3 digits and also when there is already a comma following the 3 digits.
What you might do is match 3 digits using a negative lookahead (?!,) to assert what follows is not a comma:
(\d{3}(?!,))
$("#annual_sales").on('keyup', function() {
$(this).val($(this).val().replace(/(\d{3}(?!,))/g, "$1,"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="annual_sales" type="text" />
If you don't want the comma at the end of the line you could use an alternation in the negative lookahead that asserts what follows is neither a comma or the end of the line (\d{3}(?!,|$))
$("#annual_sales").on('keyup', function() {
$(this).val($(this).val().replace(/(\d{3}(?!,|$))/g, "$1,"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="annual_sales" type="text" />
You need to strip the previously added "," from the value on beforehand like below.
$("#annual_sales").on('keyup', function () {
$(this).val($(this).val().replace(new RegExp(",", "g"), ""));
$(this).val( $(this).val().replace(/(\d{3})/g, "$1,") );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="annual_sales" type="text" />
Honestly, I think the best and most straightforward way to accomplish this is not to rely on directly using regex substitution to add a comma. Because regular expressions run from left to right, and in this case we want to parse from right to left, there's really no easy way to do this.
Instead, I would recommend using javascript to do the heavy lifting:
$("#annual_sales").on('keyup', function () {
var value = $(this).val();
var match = value.match(/[0-9,.$]+/); // Match any chars seen in currency
var new_value = "";
if (match) {
var digits = match[0].match(/\d/g); // Match single digits into an array
if (digits.length > 3) {
for (var i = digits.length - 3; i > 0; i = i - 3) {
// Start at 3 less than the length,
// continue until we reach the beginning,
// step down at intervals of 3
digits.splice(i, 0, ","); // Insert a comma
}
new_value = digits.join("");
$(this).val(new_value);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="annual_sales" type="text" />
With this function, you could expand its handling of currency values, such as prepending the value with a dollar sign, or also splitting on a decimal point and forcing two digits following it.
Edit: Scott's answer is a much shorter version of what I am suggesting here (very nice, by the way).
Well, you coul've just use this simple trick :
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
let label = data.labels[tooltipItem.index];
let value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
return ' ' + label + ' : ' + value.replace(/(.)(?=(.{3})+$)/g,"$1,");
}
}
}
Related
i've just build a javascript function with a regex control that allows 3 numbers and one dot.
function restrictNumber(e) {
var newValue = this.value.replace(new RegExp(/^(?!^(?:\d{1,3}|\d(?:\d?\.\d?|\.\d{2}))$).*/, 'gm'), "");
this.value = newValue;
}
$('.decimal').on('input', restrictNumber);
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<input class="decimal" type="text">
The specs of the regex are:
max. 3 numbers
only one or no dot
dot can be anywhere
Here is a regex demo for it: https://regex101.com/r/3Ru1O3/3/
i tried to "block" the input when a char is put in that isn't fitting. But when i try to test it deletes my hole string.
How can i change that behaviour that i just can't set new numbers put the string isnt vanishing.
You didn't say much about your actual requirements, as in, if the decimal is required at a certain place value, etc.. but based on what your existing regex does, it could definitely be shortened.
function restrictNumber(e) {
var newValue = this.value.replace(/[^\d\.]/, "").substr(0,4);
this.value = newValue;
}
$('.decimal').on('input', restrictNumber);
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<input class="decimal" type="text">
I have a input field which is a percent value, i am trying for it to display as % when not focused in and when focused in it will loose the %, also the input field needs to avoid chars on it. I'm using a type"text" input field with some jQuery.
$(document).ready(function() {
$('input.percent').percentInput();
});
(function($) {
$.fn.percentInput = function() {
$(this).change(function(){
var c = this.selectionStart,
r = /[^0-9]/gi,
v = $(this).val();
if(r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
});
$(this).focusout(function(){
$(this).val(this.value + "%");
});
$(this).focusin(function(){
$(this).val(this.value.replace('%',''));
});
};
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="percent" value="2"></input>
<input class="percent" value="4"></input>
on the snippet it does not behave the same as on my app, not sure why but the intended result is for it to erase any char that is not a digit or "only" 1 % sign.
Would change this approach only slightly:
use keypress (and eventually paste) to block invalid characters
use parseFloat (or int if you don't allow decimals) to remove leading 0's --> '00009.6' => '9.6%'
However I'd use <input type="number"> (btw: </input> closing tag is invalid HTML)
these days with a % sign just after the input. (number type has better display on mobile)
(function($) {
$.fn.percentInput = function() {
$(this)
// remove formatting on focus
.focus(function(){
this.value = this.value.replace('%','');
})
// add formatting on blur, do parseFloat so values like '00009.6' => '9.6%'
.blur(function(){
var r = /[^\d.]/g,
v = this.value;
this.value = parseFloat(v.replace(r, '')) + '%';
})
// prevent invalid chars
.keypress(function(e) {
if (/[^\d.%]/g.test(String.fromCharCode(e.keyCode)))
e.preventDefault();
});
};
})(jQuery);
$(document).ready(function() {
$('input.percent').percentInput();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="percent" value="2%">
<input class="percent" value="4%">
It is my understanding that the snippet you provided is the desired behavior, but your app isn't behaving in the desired way you've demonstrated. So, the question is: what's different between this snippet and your app? Does your app throw any errors into the console?
When I encounter problems like this, I'll usually run my page through an HTML validator. Sometimes, invalid html can corrupt more than you'd think.
When I put your html into a standard HTML5 template, the validator finds these errors in your snippet:
Basically, it is saying that you don't need </input>. Do this instead:
<input class="percent" value="2">
<input class="percent" value="4">
Perhaps this is completely unrelated, but I thought I'd mention it. I'd put your actual app through the html validator to see if you find more errors that could be ultimately corrupting your javascript's ability to achieve the desired behavior showcased by your snippet.
UPDATE** Using the solutions provided below I added this with no luck?
<script>
$('.LogIn_submit').on('click',function(){
var value=$('#Log_In_group_2_FieldB').val();
value=value.replace(/^\s\d{6}(?=\-)&/, '')
alert(value);
});
</script>
Here are the form elements if, hoping it's a simple fix:
<input id="Log_In_group_2_FieldB" name="Log_In_group_2_FieldB" type="password" value="<?php echo((isset($_GET["invalid"])?ValidatedField("login","Log_In_group_2_FieldB"):"".((isset($_GET["failedLogin"]) || isset($_GET["invalid"]))?"":((isset($_COOKIE["RememberMePWD"]))?$_COOKIE["RememberMePWD"]:"")) ."")); ?>" class="formTextfield_Medium" tabindex="2" title="Please enter a value.">
<input class="formButton" name="LogIn_submit" type="submit" id="LogIn_submit" value="Log In" tabindex="5">
/***** Beginning Question ******/
Using this question/answers's fiddle I can see how they used javascript like this:
$('.btnfetchcont').on('click',function(){
var value=$('#txtCont').val();
value=value.replace(/^(0|\+\d\d) */, '')
alert(value);
});
I currently have a value that starts with 6 characters, ends in a dash and the up to 3 digits can follow the dash.
Exmaple 1: 123456-01
Example 2: 123456-9
Example 3: 123456-999
I've tried to insert a - in the value.replace cod with no luck. How do I remove the - and any values after this on submit so that I'm only submitting the first 6 digits?
Seems that you want to have only first 6 characters from the string.
Use .split() or substring(start, end) to get the parts of string.
var string = "123456-01";
console.log(string.split('-')[0]);
console.log(string.substring(0,6));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can use split instead of regex
value=value.split("-")[0];
fix for your regex
/(-[0|\+\d\d]*)/g
function extractNumber(value){
return value.replace(/(-[0|\+\d\d]*)/g, '');
}
console.log(extractNumber("123456-01"));
console.log(extractNumber("123456-9"));
console.log(extractNumber("123456-999"));
Edit: the .split('-') answer is better than the following, imo.
Assuming you always want just the first 6 characters, something like this should do what you want:
$('.btnfetchcont').on('click',function(){
var value = $('#txtCont').val();
value = value.substr(0, 6);
alert(value);
});
or combine the two lines:
var value = $('#txtCont').val().substr(0, 6);
Read about .substr() here.
If you want to get everything before the dash, do something like this:
var value = $('#txtCont').val().match(/(\d*)-(\d*)/);
value is now an array where value[0] is the original string, value[1] is every digit before the dash, and value[2] is every digit after the dash.
This works for digits only. If you want any character instead of just digits, replace \d with .. i.e: .match(/(.*)-(.*)/).
I've been trying to remove the last word of an input value using the following code:
$('#buttonid').on('click',function () {
var textVal = $('#inputid').val();
$('#inputid').val(textVal.substring(0,textVal.length - 1));
});
This code removes only one letter from the word. I know I can delete the whole word by specifying the number of its letter in textVal.length - 1. However, the word is not static, so I want to use something that removes any last word in the input value.
Edit, Note: Words are separated by dots, not spaces.
Any suggestions?
You can use lastIndexOf method to find a position of the last dot separating last word:
$('#buttonid').on('click', function () {
var textVal = $('#inputid').val();
$('#inputid').val(textVal.substring(0, textVal.lastIndexOf('.')));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="buttonid">Remove</button>
<input type="text" id="inputid">
You can also make your code a little cleaner if you don't reselect the same element again but use a function in the val method:
$('#buttonid').on('click', function () {
$('#inputid').val(function() {
return this.value.substring(0, this.value.lastIndexOf('.'));
});
});
Bonus point. If you want you can use very simple regular expression (although it might be overkill here, but regexp is more reliable then '.' in lastIndexOf) to remove everything after the last word boundary, for example:
$('#inputid').val(function() {
return this.value.replace(/\b.\w*$/, '');
});
Use lastIndexOf(' ') instead of length - 1. The former will take the last index of a space (which signifies the last word, barring any edge cases you may have) and use it as the end point for your substring.
The latter is supposed to only give you the index of the last letter, since calling textVal.length would result in the number of actual characters in the string, not words.
$('#inputid').val(textVal.substring(0, textVal.lastIndexOf(' '));
Another option would be to transform the text to an array, and pop() it, to remove the last element. Then, rejoining it using space as a separator.
$('#buttonid').on('click', function () {
var textVal = $('#inputid').val().split(' ');
textVal.pop();
$('#inputid').val(textVal.join(' '));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="inputid"></textarea><br>
<button id="buttonid">Remove Word</button>
You can use the lastIndexOf method to get the last index of occurring peroid. Here's the code:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$("#buttonid").on('click',function ()
{
//get the input's value
var textVal = $('#inputid').val();
var lastIndex = textVal.lastIndexOf(".");
$('#inputid').val(textVal.substring(0,lastIndex));
});
});
</script>
</head>
<body>
<input type="button" id="buttonid" value="Go">
</input>
<input type="text" id="inputid" value="Anything.could.be">
</input>
</body>
</html>
I realized a software application management invoicing after having tested my program I noticed the following error:
my table in sqlserver contains: price numeric (6,2)
the user of my program enter price as 555.00 is good.
but when he put 555555 it's error, so I need to specify the mask where the mantissa is optional 0 to 999 and the decimal part is programmable 2 or 3 according to choice of the user, I'm using JQuery Masked input plugin and I have not found good regular expression, please, help, I'm working with jsp / servlet.
You can use jquery numeric for numbers.
The current version does allow what you're looking for but someone has changed the code a little bit and it works:
HTML
<input class="numeric" type="text" />
JQuery
$(".numeric").numeric({ decimal : ".", negative : false, scale: 3 });
This is the whole source.
And I've prepared this fiddle so you can see how it works.
using jQuery input mask plugin (6 whole and 2 decimal places):
HTML:
<input class="mask" type="text" />
jQuery:
$(".mask").inputmask('Regex', {regex: "^[0-9]{1,6}(\\.\\d{1,2})?$"});
I hope this helps someone
You can do it using jquery inputmask plugin.
HTML:
<input id="price" type="text">
Javascript:
$('#price').inputmask({
alias: 'numeric',
allowMinus: false,
digits: 2,
max: 999.99
});
https://codepen.io/vladimir-vovk/pen/BgNLgv
Use tow function to solve it ,Very simple and useful:
HTML:
<input class="int-number" type="text" />
<input class="decimal-number" type="text" />
JQuery:
//Integer Number
$(document).on("input", ".int-number", function (e) {
this.value = this.value.replace(/[^0-9]/g, '');
});
//Decimal Number
$(document).on("input", ".decimal-number", function (e) {
this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');
});
or also
<input type="text" onkeypress="handleNumber(event, '€ {-10,3} $')" placeholder="€ $" size=25>
with
function handleNumber(event, mask) {
/* numeric mask with pre, post, minus sign, dots and comma as decimal separator
{}: positive integer
{10}: positive integer max 10 digit
{,3}: positive float max 3 decimal
{10,3}: positive float max 7 digit and 3 decimal
{null,null}: positive integer
{10,null}: positive integer max 10 digit
{null,3}: positive float max 3 decimal
{-}: positive or negative integer
{-10}: positive or negative integer max 10 digit
{-,3}: positive or negative float max 3 decimal
{-10,3}: positive or negative float max 7 digit and 3 decimal
*/
with (event) {
stopPropagation()
preventDefault()
if (!charCode) return
var c = String.fromCharCode(charCode)
if (c.match(/[^-\d,]/)) return
with (target) {
var txt = value.substring(0, selectionStart) + c + value.substr(selectionEnd)
var pos = selectionStart + 1
}
}
var dot = count(txt, /\./, pos)
txt = txt.replace(/[^-\d,]/g,'')
var mask = mask.match(/^(\D*)\{(-)?(\d*|null)?(?:,(\d+|null))?\}(\D*)$/); if (!mask) return // meglio exception?
var sign = !!mask[2], decimals = +mask[4], integers = Math.max(0, +mask[3] - (decimals || 0))
if (!txt.match('^' + (!sign?'':'-?') + '\\d*' + (!decimals?'':'(,\\d*)?') + '$')) return
txt = txt.split(',')
if (integers && txt[0] && count(txt[0],/\d/) > integers) return
if (decimals && txt[1] && txt[1].length > decimals) return
txt[0] = txt[0].replace(/\B(?=(\d{3})+(?!\d))/g, '.')
with (event.target) {
value = mask[1] + txt.join(',') + mask[5]
selectionStart = selectionEnd = pos + (pos==1 ? mask[1].length : count(value, /\./, pos) - dot)
}
function count(str, c, e) {
e = e || str.length
for (var n=0, i=0; i<e; i+=1) if (str.charAt(i).match(c)) n+=1
return n
}
}
Now that I understand better what you need, here's what I propose. Add a keyup handler for your textbox that checks the textbox contents with this regex ^[0-9]{1,14}\.[0-9]{2}$ and if it doesn't match, make the background red or show a text or whatever you like. Here's the code to put in document.ready
$(document).ready(function() {
$('selectorForTextbox').bind('keyup', function(e) {
if (e.srcElement.value.match(/^[0-9]{1,14}\.[0-9]{2}$/) === null) {
$(this).addClass('invalid');
} else {
$(this).removeClass('invalid');
}
});
});
Here's a JSFiddle of this in action. Also, do the same regex server side and if it doesn't match, the requirements have not been met. You can also do this check the onsubmit event and not let the user submit the page if the regex didn't match.
The reason for not enforcing the mask upon text inserting is that it complicates things a lot, e.g. as I mentioned in the comment, the user cannot begin entering the valid input since the beggining of it is not valid. It is possible though, but I suggest this instead.
Try imaskjs. It has Number, RegExp and other masks. Very simple to extend.
If your system is in English, use #Rick answer:
If your system is in Brazilian Portuguese, use this:
Import:
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.15/jquery.mask.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.2.6/jquery.inputmask.bundle.min.js"></script>
HTML:
<input class="mask" type="text" />
JS:
$(".mask").inputmask('Regex', {regex: "^[0-9]{1,6}(\\,\\d{1,2})?$"});
Its because in Brazilian Portuguese we write "1.000.000,00" and not "1,000,000.00" like in English, so if you use "." the system will not understand a decimal mark.
It is it, I hope that it help someone. I spend a lot of time to understand it.