I'm trying to put a comma on a textbox that should only accept numbers. What I did is instead of using type="numbers", I limited the textbox to only accept number keyCodes.
$('#salary').keydown(function (e) {
var keyCode = e.which;
if (keyCode != 8 && keyCode != 9 && keyCode != 13 && keyCode != 37 && keyCode != 38 && keyCode != 39 && keyCode != 40 && keyCode != 46 && keyCode != 110 && keyCode != 190) {
if (keyCode < 48) {
e.preventDefault();
} else if (keyCode > 57 && keyCode < 96) {
e.preventDefault();
} else if (keyCode > 105) {
e.preventDefault();
}
}
});
What I want is that after the input is edited(out of focus), the textbox automatically shows commas similar to this value:
1,000,000.00
I am clueless on what to do or use to add comma's on the textbox.
$( "#salary" ).blur(function() {
$( "#salary" ).val( parseFloat($( "#salary" ).val(), 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString());
});
Try this solution for add comma in numbers
$('#salary').keydown(function (){
var x = $('#salary').val();
$('#salary').val(addCommas(x));
function addCommas(x) {
var parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
}
});
Could you please try with script below. Comma will be remove on click on textbox and thousand seperator will be added after focus out
$( "#salary" ).click(function() {
$( "#salary" ).val( $("#salary").val().replace(/,/g, ''));
});
$( "#salary" ).blur(function() {
$( "#salary" ).val( addCommas($( "#salary" ).val());
});
function addCommas(nStr) {
nStr += '';
var x = nStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
for minus and integer only
$("#amount").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.preventDefault();
}
});
for integer only
$("#amount").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.preventDefault();
}
});
not to display the comma when focus in
$("#amount").focus(function () {
var str = $(this).val();
$(this).val(str.replace(/,/g,''));
});
to display the comma when focus out
$("#amount").focusout(function () {
if ($(this).val().search(",") > 0){
return false;
} else {
if ($(this).val()) {
var add_comma = new Intl.NumberFormat().format($(this).val());
$(this).val(add_comma);}}
});
Related
I have to allow only Debit/Credit card number format in asp.net textbox. Below is a sample screenshot-
Please let me know how to do this with asp.net textbox and I don't have to use validators.
Note: I only have to allow numbers and after every 4 numbers there
should be a hyphen(-).
I would strongly recommend you not to reinvent the bicycle and use jQuery inputmask plugin which will let you do the following:
$("input").inputmask({
mask: "9999 9999 9999 9999",
placeholder: ""
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.inputmask/3.3.4/jquery.inputmask.bundle.js"></script>
<input type="text"/>
Note that in this code I assumed that card number consists of 4 groups of 4 digits each, and it is not always true - it depends on expected cards' payment systems, country etc.
You can easily achieve any result by adding or removing digits in mask.
You can do the following:
<input type="text" onkeypress="return allowNumbersAndHyphen(event)">
function allowNumbersAndHyphen(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
//allowing numbers, left key(37) right key(39) backspace(8) delete(46) and hyphen(45)
var length = $('input').val().length;
if (((charCode == 37 || charCode == 39 || charCode == 8 || charCode == 46 || charCode == 45) || !(charCode > 31 && (charCode < 48 || charCode > 57))) && length <19)
{
return true;
}
else{
return false;
}
}
//put hyphens atomatically
$(document).ready(function(){
$('input').on('keypress', function() {
var temp = $(this).val();
if (temp.length == 4 || temp.length == 9 || temp.length == 14) {
$('input').val(temp + '-');
}
});
$('input').on('blur', function() {
var regex = /^[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{4}$/;
var cardNumber = $(this).val();
if(regex.test(cardNumber)) {
//success
alert('successful');
}
else {
//show your error
alert('Error');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- begin snippet: js hide: false console: true babel: false -->
Using vanilla javascript
document.getElementById('inp1').onkeypress = verify;
console.clear();
function isKeyValid(key) {
if(key > 47 && key < 58) return true
else if(key === 45) return true;
else return false;
}
function isValidCard(arr, isDash) {
const last = arr[arr.length - 1];
if(last.length === 4 && !isDash) return false;
else if(isDash && last.length !== 4) return false;
else if(isDash && arr.length === 4) return false;
else return true;
}
function verify(e) {
const key = e.keyCode || e.which;
const isDash = key === 45;
const val = e.target.value;
const input = val.split('-');
if (!isKeyValid(key) || !isValidCard(input, isDash)) {
return e.preventDefault();
}
// ...do something
}
after press key "," i append new input, when i use backspace last input is removed, but after delete all inputs when i press again "," code return all inputs, not one. how fix it?
http://jsfiddle.net/3r79hyoL/
$(".multipleField").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(",", ""));
$(this).first().clone().appendTo(".multipleFields").focus().val("");
event.preventDefault();
$(this).addClass('makeBorder');
replaceAndCopy();
}
if (key == 8) {
e.preventDefault();
if ($(".multipleFields").last().val() == "" && $(".multipleField").length > 1) {
$(".multipleField").last().remove();
$(".multipleField").last().focus();
}
}
});
function replaceAndCopy() {
$(".multipleField").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(",", ""));
$(this).clone().appendTo(".multipleFields").focus().val("");
$(this).addClass('makeBorder');
replaceAndCopy();
}
if (key == 8) {
if ($(".multipleFields").last().val() == "" &&
$(".multipleField").length != 1) {
$(".multipleField:last").remove();
e.preventDefault();
$(".multipleField").last().focus();
}
}
});
}
The problem is that you are attaching new event listeners to every input. So when you go back to an input that is not the last one the event is fired more than one time.
function replaceAndCopy() {
// Add new event listener to all inputs, instead of the last
// $(".multipleField").keyup(function(e) {
// Change to
$(".multipleField").last().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(",", ""));
$(this).clone().appendTo(".multipleFields").focus().val("");
$(this).addClass('makeBorder');
replaceAndCopy();
}
if (key == 8) {
if ($(".multipleFields").last().val() == "" && $(".multipleField").length != 1) {
$(".multipleField:last").remove();
e.preventDefault();
$(".multipleField").last().focus();
}
}
});
I have a condition to allow user to input only 2 decimal points number and restrict the alphabets and other characters. I used the following function:
function isNumberKeyOnlyWithDecimalFormat(event,value,id){
var val = value;
if (event.shiftKey === true) {
event.preventDefault();
}
if ((event.keyCode >= 48 && event.keyCode <= 57) ||
(event.keyCode >= 96 && event.keyCode <= 105) ||
event.keyCode == 8 ||
event.keyCode == 9 ||
event.keyCode == 37 ||
event.keyCode == 39 ||
event.keyCode == 46 ||
event.keyCode == 190) {
} else {
event.preventDefault();
}
if(val.indexOf('.') !== -1 && event.keyCode == 190){
event.preventDefault();
}
if ((pointPos = $('#'+id).val().indexOf('.')) >= 0){
$('#'+id).attr("maxLength", pointPos+3);
}
else
$('#'+id).removeAttr("maxLength");
}
It is working fine while first time adding. But it restricts the if i want to edit the digits if it has already 2 decimal place. Can anyone help with this?
Try this. It will check the value each time the focus is gone from the input field, but you can use any event you like. It will parse the value as a float, and then round it to 2 decimal points.
Here is the fiddle: http://jsfiddle.net/sAp9D/
HTML:
<input type="text" id="the_id" />
JavaScript:
var input_field = document.getElementById('the_id');
input_field.addEventListener('change', function() {
var v = parseFloat(this.value);
if (isNaN(v)) {
this.value = '';
} else {
this.value = v.toFixed(2);
}
});
Your question is very hard to understand but if you want to check that a string has only 2 decimals then you can just do this
if( value.match(/\./g).length === 2 ) {
// Number has 2 decimals eg. 1.2.3
} else {
// Number is incorrect eg. 1.2.3.4
}
or if you want 1.2 then
if( value.match(/\./g).length === 1 ) {
// Code....
}
I use the following
// This function will only allow digits
function numericFormat( fld , e , extraStrCheck )
{
var sep = 0;
var key = '';
var i = j = 0;
var len = len2 = 0;
var strCheck = '0123456789';
if ( extraStrCheck )
strCheck += extraStrCheck;
var aux = aux2 = '';
var whichCode = (window.Event) ? e.which : e.keyCode;
if (whichCode == 13) return true; // Enter
if (whichCode == 8) return true; // Backspace
if (whichCode == 0) return true; // Null
if (whichCode == 9) return true; // Tab
key = String.fromCharCode(whichCode); // Get key value from key code
if ( strCheck.indexOf(key) == -1 ) return false; // Not a valid key
var x = new String(fld.value);
if ( key == '.' )
{
var exp = /\./;
var a = x.search(exp);
if ( a != -1 ) return false;
}
}
// samer code on change or on blur event
function allow2decimal(obj){
var v = parseFloat($(obj).val());
if (isNaN(v)) {
$(obj).value = '';
} else {
newVal = v.toFixed(2);
if(newVal >= 100){
$(obj).val( 100 );
}else{
$(obj).val(newVal);
}
}
}
//usage
<input
onkeypress="return numericFormat( this , event , '.');"
onchange="allow2decimal(this)"
value="0.1"
id="factory_silk" name="factory_silk" />
<html>
<head>
<script type="text/javascript">
function NumAndTwoDecimals(e, field) {
var val = field.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)) {
}
else {
val = re1.exec(val);
if (val) {
field.value = val[0];
}
else {
field.value = "";
}
}
}
</script>
</head>
<body>
<input type="text" name="text" onkeyup="NumAndTwoDecimals(event , this);">
</body>
</html>
$('.number').keypress(function(evt){
var str = $(this).val();
var index = str.indexOf('.');
if(index==-1){index=0;}else{index= index+1;}
var extrapoint = str.indexOf('.',index);
if(extrapoint>0){$(this).val(str.slice(0,-1));}
var charCode = (evt.which) ? evt.which : event.keyCode;
if(charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
var validNumber = new RegExp(/^\d*\.?\d*$/);
var lastValid = $(this).val();
if (validNumber.test($(this).val()))
{
lastValid = $(this).val();
}
else
{
$(this).val(lastValid);
}
});
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));
});
In following example I am attempting to change the charCode of the key pressed but it does not change. When I press "a" I want it to type "b". What am I doing wrong?
$("#target").keypress(function(event) {
if ( event.which == 97 ) {
//alert('pressed a');
//event.preventDefault();
event.keyCode = 98;
event.charCode = 98;
event.which = 98;
}
});
You can't override the keycode in the event object...
Look at this snippet:
$('#target').keypress(function(e){
if (e.which == 97)
this.value = this.value + String.fromCharCode(98)
else
this.value = this.value + String.fromCharCode(e.which)
....
return false;
})
replace comma and dash to slash.
$('.pdate').on('keypress', function (e) {
var ch = String.fromCharCode(e.keyCode);
$("div").text(e.keyCode)
if (!((ch >= '0' && ch <= '9') ||
ch == '/' || ch == ',' || ch == '-')) {
return false;
}
if (ch == ',' || ch == '-')
{
var val = $(this).val();
var s = this.selectionStart;
val = val.slice(0, s) + "/" + val.slice(s, val.length);
$(this).val(val)
this.selectionStart = s +1;
this.selectionEnd = s +1;
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" class="pdate" />
<div></div>