Changing the charCode of the key pressed - javascript

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>

Related

Using Jquery to add comma's on textbox

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);}}
});

KnockoutJs binding for input tag to format number with comma

Is there available binding to format an input value from 123456789 to 123,456,789. The binding should work on every keypress and validate the value if it is a valid number. I found this solution but it is not formatting on keypress.
I ended up creating custom binding. It only works on IE10 and above for the usage of event input.
Here's the code. See fiddle here.
String.prototype.countOccurence = function(char){
return (this).split(char).length - 1;
}
$.fn.selectRange = function(start, end){
if(end === undefined)
end = start;
return this.each(function() {
if("selectionStart" in this){
this.selectionStart = start;
this.selectionEnd = end;
} else if(this.setSelectionRange)
this.setSelectionRange(start, end);
else if(this.createTextRange){
var range = this.createTextRange();
range.collapse(true);
range.moveEnd("character", end);
range.moveStart("character", start);
range.select();
}
});
};
ko.helper = {};
ko.helper['toNumber'] = function (value, limit){
limit = limit || 10;
var num = Number((value || "").toString().replace(/[^0-9]/gi, "").substring(0, limit));
return num;
}
ko.bindingHandlers['formatNumber'] = {
init: function(element, valueAccessor, allBindings){
var value = valueAccessor();
var limit = allBindings.get("limit") || 10; //billion
var position = 0;
var navigationKeys = [33, 34, 35, 36, 37, 38, 39, 40, 9];
var isBackSpace = false;
var oldLengthValue = (value() || "").toString().length;
function isKeyControls(e){
if(e.ctrlKey && (e.keyCode == 67 || e.keyCode == 86 || e.keyCode == 65)){
return true;
}
if(e.shiftKey && (e.keyCode == 37 || e.keyCode == 39)){
return true;
}
return false;
}
$(element).on("keyup", function(e) {
if(this.selectionStart == this.value.length)
return;
if(isKeyControls(e) || e.shiftKey){
return;
}
var navigation = (e.keyCode == 37
? -1
: e.keyCode == 39
? 1
: 0);
var customSelectionStart = this.selectionStart; // + navigation;
//customSelectionStart = customSelectionStart
var positionMinusOne = customSelectionStart == 0
? -1
: customSelectionStart;
positionMinusOne = positionMinusOne + (positionMinusOne == -1 ? 0 : navigation);
var previousCharacter = positionMinusOne == -1
? ""
: this.value.substring(customSelectionStart - 1, customSelectionStart);
if(previousCharacter == ","){
$(this).selectRange(customSelectionStart +
(isBackSpace ? -1 : 0));
}
var currentCommaOccurence = this.value.countOccurence(",");
var commaValue = oldLengthValue > currentCommaOccurence ? -1
: oldLengthValue < currentCommaOccurence ? 1
: 0;
if(commaValue != 0){
$(this).selectRange(customSelectionStart +
commaValue);
}
oldLengthValue = this.value.countOccurence(",");
});
$(element).on("keydown", function (e) {
if (isKeyControls(e)) {
return;
}
var navigation = (e.keyCode == 37
? -1
: e.keyCode == 39
? 1
: 0);
var customSelectionStart = this.selectionStart + navigation;
//customSelectionStart = customSelectionStart
var positionMinusOne = customSelectionStart == 0
? -1
: customSelectionStart;
positionMinusOne = positionMinusOne + (positionMinusOne == -1 ? 0 : navigation);
var previousCharacter = positionMinusOne == -1
? ""
: this.value.substring(customSelectionStart - 1, customSelectionStart);
if(previousCharacter == ",")
$(this).selectRange(customSelectionStart);
isBackSpace = e.keyCode == 8;
if(isBackSpace)
return;
//Navigation
if(navigationKeys.some(function(key) {
return key == e.keyCode;
}))
return;
//Other Keys
var isNumber = (e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 96 && e.keyCode <= 105);
var isLimit = (limit + parseInt(limit / 3)) == this.value.length;
if(!(isNumber)
|| isLimit){
e.preventDefault();
return;
}
});
$(element).on("input", function(e, a, b, c) {
console.log(this.selectionStart, this.selectionEnd);
var convertedValue = ko.helper.toNumber(this.value, limit);
var formatted = convertedValue
? ko.helper.toNumber(this.value, limit).toLocaleString()
: "";
position = this.selectionStart == this.value.length
? formatted.length
: this.selectionStart;
value(convertedValue || "");
this.value = formatted;
$(this).selectRange(position);
});
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$(element).off();
});
ko.bindingHandlers["formatNumber"].update(element, valueAccessor, allBindings);
},
update: function(element, valueAccessor, allBindings){
var value = valueAccessor();
var limit = allBindings.get("limit") || 10; //billion
var convertedValue = ko.helper.toNumber(value(), limit);
var formatted = convertedValue
? ko.helper.toNumber(value(), limit).toLocaleString()
: "";
element.value = formatted;
}
};

textbox validation for two numbers and two decimal values in asp.net with javascript

How to check textbox validation for two numbers and two decimal values in asp.net with javascript?
For Example whien i press the key in textbox it should allow me only xx.xx format, example : 12.25, 25.50,48.45 etc.
I got the answer.
<div>
<asp:TextBox ID="TextBox2" runat="server"
onkeypress="return isDecimalNumber(event,this);" MaxLength="5">
</asp:TextBox>
</div>
<script type="text/javascript" language="javascript">
var count = 0;
function isDecimalNumber(evt, c) {
count = count + 1;
var charCode = (evt.which) ? evt.which : event.keyCode;
var dot1 = c.value.indexOf('.');
var dot2 = c.value.lastIndexOf('.');
if (count > 2 && dot1 == -1) {
c.value = "";
count = 0;
}
if (dot1 > 2) {
c.value = "";
}
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
else if (charCode == 46 && (dot1 == dot2) && dot1 != -1 && dot2 != -1)
return false;
return true;
}
</script>
Try this,
$('.TextBox2').keypress(function (event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
var text = $(this).val();
if ((text.indexOf('.') != -1) && (text.substring(text.indexOf('.')).length > 2)) {
event.preventDefault();
}
});
http://jsfiddle.net/hibbard_eu/vY39r/
$("#amount").on("keyup", function(){
var valid = /^\d{0,2}(\.\d{0,2})?$/.test(this.value),
val = this.value;
if(!valid){
console.log("Invalid input!");
this.value = val.substring(0, val.length - 1);
}
});

jQuery trigger key on button click

I want to make something where when you are in a input you can press a button and it will fill it with a character(depending on the button) and move onto the next input.
$('.today').keyup(function(e) {
if ($.inArray(e.keyCode, [69, 88, 191]) === -1) { // e, x, / respectively
e.preventDefault(); // don't print the character
return false;
}
var self = $(this);
var currentInput = self.data('number');
var next = $(currentInput + 1);
var previous = $(currentInput - 1);
var keyCode = e.keyCode || e.which;
var num = self.data('number') + 1;
var nom = self.data('number') - 1;
if(('input.today[data-number="' + num +'"]').length && keyCode === 40)
$('input.today[data-number="' + num +'"]').focus()
else if(('input.today[data-number="' + nom +'"]').length && keyCode === 38)
$('input.today[data-number="' + nom +'"]').focus();
else if(('input.today[data-number="' + num +'"]').length && self.val().length == self.attr('size')) {
$('input.today[data-number="' + num +'"]').focus();
}
});
$('.today').keyup(function(e) {
if ($.inArray(e.keyCode, [69, 88, 191]) === -1) {
$( this ).next().focus();
}else{
return false;
}
});

Allow to enter only 2 decimal points number

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);
}
});

Categories