Add thousand separator with JavaScript on keyup event - javascript

I am using the following JavaScript function to add thousand separator for a input number on keyup event.
$("#inputId").on('keyup', function(evt){
if (evt.which != 110 && evt.which != 190){
var n = parseFloat($(this).val().replace(/\,/g,''),10);
$(this).val(n.toLocaleString());
}
});
Most of the cases this function is working as expected, but the only issue is the input field does not accept zero after the decimal point (for example 10.01) but it does accept numbers like 10.25 . I can't figure out the reason for this behavior. Any idea?
Thanks.

Splitting on the decimal would work. Something like this. Note this is very basic starting point and does not account for the different separators in other countries/systems (ie: 10.000,00)
<script>
var myinput = document.getElementById('myinput');
myinput.addEventListener('keyup', function() {
var val = this.value;
val = val.replace(/[^0-9\.]/g,'');
if(val != "") {
valArr = val.split('.');
valArr[0] = (parseInt(valArr[0],10)).toLocaleString();
val = valArr.join('.');
}
this.value = val;
});
</script>
<input id="myinput" type="text'>

Related

JS validation allow letters and specific symbol only + change input

I am using a JS solution to allow letters and backspace only.
I want to add more options to the input, but can't see to find the right solution.
My Code:
<input id="inputTextBox">
$(document).ready(function(){
$("#inputTextBox").keypress(function(event){
var inputValue = event.which;
if(!(inputValue >= 65 && inputValue <= 123) && (inputValue != 32 && inputValue != 0)) {
event.preventDefault();
}
console.log(inputValue);
});
});
This give me the correct result of only letter input and use of backspace.
For the correct user experiece I need to add the following.
Allow input '?' , '*' and 'spacebar'.
And if possible, change the input in the form when the user typ.
So if a user typ a '?' or 'spacebar', it changes into the value '*' automatic.
Thanks in advance.
Slightly modified from this solution:
How to allow only numeric (0-9) in HTML inputbox using jQuery?
EDIT: added code to preserve position when ? and spaces are replaced
// Restricts input for the set of matched elements to the given inputFilter function.
// Modified to pass element to callback function
(function($) {
$.fn.inputFilter = function(inputFilter) {
return this.on("input keydown keyup mousedown mouseup select contextmenu drop", function() {
if (inputFilter(this)) {
this.oldValue = this.value;
this.oldSelectionStart = this.selectionStart;
this.oldSelectionEnd = this.selectionEnd;
} else if (this.hasOwnProperty("oldValue")) {
this.value = this.oldValue;
this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
} else {
this.value = "";
}
});
};
}(jQuery));
$(document).ready(function(event) {
$("#inputTextBox").inputFilter(function(el) {
var oldSelectionStart = el.selectionStart;
var oldSelectionEnd = el.selectionEnd;
var oldValue = el.value;
el.value = el.value.replace(/[* ]/g, '?'); //replace * space with ?
el.value = el.value.replace(/[^a-zA-Z?]/g, '');
if (oldValue != el.value)
el.setSelectionRange(oldSelectionStart-(oldValue.length-el.value.length), oldSelectionEnd-(oldValue.length-el.value.length));
return /^[a-zA-Z?]+?$/.test(el.value); // alphabet question only
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="inputTextBox">
Simply added a keyup function to replace the character '?' and space to *
and also added envent ids of space and '?' in your keypress function.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="inputTextBox">
<script>
$(document).ready(function(){
$("#inputTextBox").keypress(function(event){
var inputValue = event.which;
if(!(inputValue >= 65 && inputValue <= 123) && (inputValue != 32 && inputValue != 0 && inputValue != 63 && inputValue != 42 && inputValue != 32)) {
event.preventDefault();
}
});
$("#inputTextBox").keyup(function(){
var inputTxt = $('#inputTextBox').val();
inputTxt = inputTxt.replace('?', '*').replace(' ', '*')
$('#inputTextBox').val(inputTxt);
});
});
</script>
You have an issue with your code already since the 65 - 123 contains letters, but it also contains [] _ to name a few.
so you probably want 65-90 for A-Z then 97-122 for a-z 48-57 for 0-9. then check each character you want to allow, they probably wont be in a range.
If you look at the ascii chart here https://theasciicode.com.ar/ascii-printable-characters/question-mark-ascii-code-63.html you will see all the numbers you need to include (or exclude)
On the keyUp event, you could look at the value and then change the last character to the * if you wish, but remember that will change the actual value, not just mask it.
If you want it masked, you should use an <input type="password"> field, which has that behaviour by default.

Clear text field when keyup function is triggered

I’m trying to clear a text field after a keyup function is triggered.
I used a simple val('') to clear but it’s not working. Also if ever. I want my text field to not allow entering period or . on the first place, like .12.
Here is my keyup function:
$('#gross-mass').keyup(function(event) {
var currentVal = $(this).val();
if (parseFloat(currentVal) == 0.00 && (event.which == 48 || event.which == 96)) {
//currentVal = currentVal.slice(0, 3);
currentVal.val(' ');
}
$(this).val(currentVal);
});
currentVal isn't a function, it's a string. You can set its value like this:
currentVal = ' '
First of all, you need to use $(this).val(""), not currentVal.val(' '); (in my example it's just el.val("") because I have stored var el = $(this)). And you should remove this row before the end of the method: $(this).val(currentVal);, because it sets input's value back to currentVal. Here is the working example, try to type 0 for example, input's value will be cleared after keyup event:
$('#gross-mass').keyup(function(event) {
var el = $(this)
var currentVal = el.val();
if (parseFloat(currentVal) == 0.00 && (event.which == 48 || event.which == 96)) {
el.val("");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="gross-mass">

Replacing if the first number is a zero and the number is greater than 2 places

I have a calculator I'm working on and came across a problem. To combat so that users can't leave a field blank, I'm forcing a zero if the field is left empty. That's all fine, but the problem is that when the text in the field is deleted to remove the zero and enter a new number, it automatically enters zero so my new number looks like this: 05
How do i run a replace where if there is more than 2 places in the number and the first number is zero, replace the zero? Here's the code i'm using for my calculator.
$(function(){
calculate();
$('.input').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)) {
return false;
}
});
$('.input').on('keyup',function(){
if($(this).val()==''){
$(this).val('0');
}
calculate();
});
});
function calculate(){
var d6 = parseFloat(($('#d6').val()).replace(/,/g,''));
var d20 = parseFloat(($('#d20').val()).replace(/,/g,''));
var b20 = d6;
var e20 = parseFloat(($('#e20').val()).replace(/,/g,''));
var f20 = d20*e20;
var f22 = b20/f20;
var f23 = (52-f22)*f20;
$('#f20').html(formatCurrency(f20));
$('#f22').html(f22.toFixed(2));
$('#f23').html(formatCurrency(f23));
}
function formatCurrency(x) {
return '$'+x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
}
If you are essentially trying to turn it into a formatted number you could try type coercion:
'' + new Number('') // "0"
'' + new Number('0') // "0"
'' + new Number('05') // "5"
'' + new Number('0000.2') // "0.2"
Change the zeroing code to use the blur() event, i.e when the field loses focus.
$('.input').blur(function(){
if($(this).val()=='')
{
$(this).val('0');
}
});
I'm assuming that the text is removed from pressing the backspace key.
If that is the case then you keyup handler would fire when you backspace on the zero, which would detect no input, then add the zero.
First of all, you are doing it a hard way. And try this... if the user clicks on the input then it will be cleared and the user can write whatever number he wants...
$( ".input" ).focus(function() {
(this).val('');
});
In case you are using an HTML5 form you can avoid that piece of code like this:
<input type="number" placeholder="Type a number" required>
The required attribute is a boolean attribute.
When present, it specifies that an input field must be filled out.
Instead of using keyup and keypress event for checking and replacing blank to zero, use change event.
$(function(){
calculate();
$('.input').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)) {
return false;
}
});
$('.input').on('keyup',function(){
calculate();
});
$('.input').on('change',function(){
if($(this).val()==''){
$(this).val('0');
}
});
});
function calculate(){
var d6Val = ($('#d6').val() !== "")? $('#d6').val() : '0';
var d20Val = ($('#d20').val() !== "")? $('#d20').val() : '0';
var e20Val = ($('#e20').val() !== "")? $('#e20').val() : '0';
var d6 = parseFloat((d6Val).replace(/,/g,''));
var d20 = parseFloat((d20Val).replace(/,/g,''));
var b20 = d6;
var e20 = parseFloat((e20Val).replace(/,/g,''));
var f20 = d20*e20;
var f22 = b20/f20;
var f23 = (52-f22)*f20;
$('#f20').html(formatCurrency(f20));
$('#f22').html(f22.toFixed(2));
$('#f23').html(formatCurrency(f23));
}
function formatCurrency(x) {
return '$'+x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
}
One more thing. Change event only fires when you focus-out from that input.
Please let me know if you will face any issue.

not receive negative numbers

I have the following code: http://jsfiddle.net/ntywf/1987/
$(document).ready(function () {
$('input').keyup(function() {
var $th = $(this);
$th.val($th.val().replace(/[-]/g, function(str) {
//alert('You typed " ' + str + ' ".\n\nPlease use only letters and numbers.');
return '';
}));
});
});
what I want is to remove the "-" sign off when it is inserted. what happens is that the cursor is always the last decimal home. I just want this code not to let the user enter negative numbers. How can I do this? (the problem is to move the cursor within the input, since it is always sent to the last character)
You can use a KeyCode (Link) to verify what key you pressed, and use replace to remove it:
$('input').keyup(function(e) {
var code = e.keyCode || e.which;
if(code == 109 || code == 189) { //Enter keycode
//Do something
var valor = $(this).val();
$(this).val(valor.replace(/[-]/g, ''))
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text"/>
Here what I have tried.
JS
$('input').keyup(function() {
var $th = $(this).val();
$th = $th.replace(/[-]/g, "");
$(this).val($th)
console.log( $(this).val());
});
It will remove - sign from data.
This should solve your problem
What I have done is:
I have used the inbuilt HTML input field method setSelectionRange(), which sets the start and end positions of the current text selection in an element. (From MDN)
MDN Reference : https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/setSelectionRange
JS Code:
$(document).ready(function () {
$('input').keyup(function() {
var $th = $(this);
$th.val( $th.val().replace(/[-]/g, function(str) {
//alert('You typed " ' + str + ' ".\n\nPlease use only letters and numbers.');
return '';
} ) );
$('input')[0].setSelectionRange(0, 0); //this method sets the range to zero text starting from 0 index to 0 index
});
});
JSFiddle: http://jsfiddle.net/dreamweiver/ntywf/1998/
Use type = "numeric" and min="0" This way you can prevent your text-field from accepting alphabets as well. min=0 will always make sure that it will never accept -ve value.
<input type="number" min="0"/>
JSFIDDLE DEMO will be helpful to you.

Replacing comma with dot Char

I have made a calculation app in AppJs.
Basicly it is a bunch of:
<input type=number>
fields.
To make it more user friendly i thought i should replace All commas with dots, so that javascript can use the actual values to calculate.
I've tried doing this with this following pice of code:
$("input[type=number]").keyup(function(e){
var key = e.which ? e.which : event.keyCode;
if(key == 110 || key == 188){
e.preventDefault();
var value = $(this).val();
$(this).val(value.replace(",","."));
}
});
In explorer 9, this works as expected: see fiddle
But since App.js uses chromium i guess this is a something thats happens in chromium. How can I work around this?
This is what happens in my app:
When you enter a number containing a comma char. The comma char is moved to the right and when the input box loses focus, the comma is removed (Probably since the comma char isn't allowed in type=number)
When you get the value of an <input type=number> but it isn't valid, then a blank string is returned. You could check this by doing this:
$("input[type=number]").keyup(function(e){
var key = e.which ? e.which : event.keyCode;
if(key == 110 || key == 188){
e.preventDefault();
var value = $(this).val();
console.log(value === "");
$(this).val(value.replace(",","."));
}
});
It will print true every time. Therefore, you need to
Since, on the keyup event, the input has already changed, you must change it to a keydown or keypress event.
Change value.replace(",", ".") to value + "." (since there will be no ",").
Actually, you need to insert it where the cursor is. I'll update that when I have time.
Finished code:
$("input[type=number]").keydown(function (e) {
var key = e.which ? e.which : event.keyCode;
if (key == 110 || key == 188) {
e.preventDefault();
var value = $(this).val();
console.log(value);
$(this).val(value + ".");
}
});
A better idea might be to make it <input type=text> and validate manually if you really need this feature.
It's probably better not to mess with the actual data in the input field but reformat internally before reading, accessing the value through a getter like this:
var getInputNumber = function(inputid) {
return $(inputid).val().replace(",", ".");
};
$("input").keydown(function (e) {
var key = e.which ? e.which : event.keyCode;
if (key == 110 || key == 188) {
var value = $(this).val();
if (!isNaN(value)) {
e.preventDefault();
$(this).val(value + ".");
}
}
});

Categories