text box decimal format fixing - javascript

I have a simple text box and I am entering number value to this.And i want to format the number value to two decimal places.Like If i enter the 10 in the text box and after pressing entering or leaving textbox it should be converted into 10.00.Please tell me if there exist any possibility to do this using javascript or vb.net or asp.net property of textbox.I already tried in JavaScript on enter key or tab key press but it convert it into 10.00 each time when i press the enter or tab.here is code
//Make Formatting with .00
document.onkeydown = function disableKeys() {
if( typeof event != 'undefined' ) {
if( (event.keyCode == 9) ||
(event.keyCode == 13) ) {
var a;
var b;
a=parseFloat(document.getElementById('txtpkrusd').value,10);
b=parseFloat(document.getElementById('txtRatelb').value,10);
document.getElementById('txtpkrusd').value=formatNumber(a);
document.getElementById('txtRatelb').value=formatNumber(b);
}
};
};

var num = 10;
var result = num.toFixed(2); //will give 10.00
Examples

hiya hope this helps: (apart from my comment above i.e. to round use .toFixed(num))
demo (enter the number and press enter) : http://jsfiddle.net/6wG26/5/ OR Enter and Tab keys both here http://jsfiddle.net/Mtw7c/7/
Please; let me if this is not what you want I will delete my post; but this will help you.
Since you dint had much code up I have made forked sample here:
**HTML:**
<input type="text" name="one" class="currency">
**JQuery code:**
(function($) {
$.fn.currencyFormat = function() {
this.each( function( i ) {
$(this).change( function( e ){
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixed(2);
});
});
return this; //for chaining
}
})( jQuery );
$( function() {
$('.currency').currencyFormat();
});​
OR ENter key & Tab key here: http://jsfiddle.net/Mtw7c/7/
$('.currency').live('keydown', function(e) {
var key = e.keyCode || e.which;
if (key== 9 || key == 13) {
e.preventDefault();
if( isNaN( parseFloat( this.value ) ) ) return;
this.value = parseFloat(this.value).toFixed(2);
// call custom function here
}
});
​
hope this helps and it will be good if you read the following link - sample taken from here but to make it sample for you, In jQuery, what's the best way of formatting a number to 2 decimal places?
You can always put validation for the number only text box & other amendments, Hope this helps mate, cheers!!

Related

Extend function to prevent paste inside an input field

I'm currently trying to prevent typing everything instead of numbers and points inside a an input field. The problem is that pasting letter or strange things still works. So is there a way to prevent it in my function?
I could do a HTML part like onpaste="return false;" but maybe there is a better solution that uses my available function. Thanks for your help!
jQuery( document ).ready( function ( $ ) {
$( document ).on( "keypress keyup paste", "#test", function ( event ) {
let input = $( this ).val();
console.log(input);
console.log(event.which);
if ( ( event.which !== 46 || $( this ).val().indexOf( '.' ) !== -1 ) && ( event.which < 48 || event.which > 57 ) ) {
event.preventDefault();
} else if ( ( input.indexOf( '.' ) !== -1 ) && ( input.substring( input.indexOf( '.' ) ).length > 2 ) ) {
event.preventDefault();
}
} );
} );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="test"/>
Edit:
I also found out that the sign ^ still works too but has no event? How is this possible?
The idea is to only allow numbers with points and two decimals like 22222.22 for example.
Edit 2:
Input type number is not working because it allows more than just numbers and points.
<input type="number"/>
Somehow below code handles ctrlX, ctrlV, ^, and allows decimal input
const input = document.querySelector('input')
let old = input.value
input.addEventListener('input', function() {
if (!this.checkValidity()) {
this.value = old
} else {
old = this.value
}
})
<input type="text" pattern="\d+(\.[\d]{0,2})?"/>
For dynamically added input (by using event delegation) we could store the old attribute on the input itself
jQuery( document ).ready( function ( $ ) {
$( document ).on( "input", "input.decimals", function ( event ) {
if (!this.checkValidity()) {
this.value = this.dataset.old || ''
} else {
this.dataset.old = this.value
}
return true
})
const pattern = '\\d+(\\.[\\d]{0,2})?'
document.querySelector('div').innerHTML += `<input class="decimals" type="text" pattern="${pattern}"/>`.repeat(2)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div></div>
You can try to explicitly disable cut, copy, or paste functionality on targeted element (e.g: #txtInput element) using the snippet below:
$(document).ready(function(){
$('#txtInput').on("cut copy paste",function(e) {
e.preventDefault();
});
});
More on how to do this here: How to prevent pasting into input fields.
Have you tried the simple solution which is to use input of type number?
e.g. <input type="number" />
There is a caveat, the letter 'e' can be typed, i.e. Euler's Number

Input field value when selected, cannot be overwritten

I validate an input field by those patterns:
only positive numbers
only one .
only numeric values
only two decimals after .
only numbers between 0 and 100
limit input to 5 characters (0 ... 1.1 ... 10.2 ... 33.23 ... 99.99 or 100)
These validations work with my code fine. Even there is a better way to code this validation. But anyways - my issue, which I can't solve right now is - if I enter a value for example 99.99 or 100 or 23.23 and I want to change the value again by selecting / mark the entire value with my mouse for example - it will not change! If I write 2.33 and I select/mark the entire value with my mouse it will change. So it seems I'm facing a 'false' state which does not allow me to enter another digit and right now I could not find a kind of an event which detects that I select something in my input field.
I have prepared an JSFIDDLE code - where do I have my confusion?
ps: I am also aware that maybe my keypress event is overwriting the false/true states, I'm trying to solve this afterwards.
Thank you very much!
Best Regards
$('#inpNumber').on('input', function() {
var inpVal = $(this).val();
if ( inpVal > 100 || inpVal < 0 || !inpVal) {
$( "#inpNumber" ).removeClass( "is-valid" );
$( "#inpNumber" ).addClass( "is-invalid" );
} else {
$( "#inpNumber" ).removeClass( "is-invalid" );
$( "#inpNumber" ).addClass( "is-valid" );
}
});
$('#inpNumber').keypress(function (event) {
var input = $(this).val();
if ((input.indexOf('.') != -1) && (input.substring(input.indexOf('.')).length > 2)) {
event.preventDefault();
return false;
}
return isNumberRegChecked(event, this);
return isNumber(event, this);
});
function isNumberRegChecked( evt, element ) {
var inpVal = $(element).val();
// ^(\d\d?(\.\d\d?)?|100(\.00?)?)$ also possible
var checkShare = /^(\d{0,2}(\.\d{0,2})?)$/.test(inpVal);
if (checkShare == false)
return false;
return true;
}
// THE SCRIPT THAT CHECKS IF THE KEY PRESSED IS A NUMERIC OR DECIMAL VALUE.
function isNumber( evt, element ) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if ((charCode != 46 || $(element).val().indexOf('.') != -1) && // “.” CHECK DOT, AND ONLY ONE.
(charCode < 48 || charCode > 57))
return false;
return true;
}

jQuery: selectionStart returns undefined

Situation
browser
Google Chtome 69
html
<textarea id="message" name="message">
// input some messsage
</textarea>
js(jQuery)
$(function () {
$("#message").on("keydown keyup keypress change", function () {
//this part runs correctly
})
$('#message').on('keydown', function (e) {
if ((e.wich && e.wich === 13) || (e.keyCode && e.keyCode === 13)) {
var $textarea = $(this);
var sentence = $textarea.val();
var position = $textarea.selectionStart;
var length = sentence.length;
var before = sentence.substr(0, position);
var after = sentence.substr(position, length);
sentence = before + "\n" + after;
}
});
});
When I input something in the #message textarea and push Enter key in the area, nothing would happen. According to Chrome developer tool, selectionStart method seems to return Undefined.
Needs
Enter key has been made disabled in this form page in order to avoid submitting the data mitakenly.
js
function fnCancelEnter()
{
if (gCssUA.indexOf("WIN") != -1 && gCssUA.indexOf("MSIE") != -1) {
if (window.event.keyCode == 13)
{
return false;
}
}
return true;
}
However, in this textarea, I want to enable user to add a break line by pressing Enter key.
I'm sorry but I don't have much knowledge about jQuery and javascript. Please tell me how to do.
Please replace $textarea.selectionStart by $textarea.get(0).selectionStart. Then try again.

change spaces entered in input field to underscore in real time

I have an input field that should switch all spaces entered to a '_' in real time. Meaning when the user hits the spacebar in that input field a underscore is being displayed instead of a space. I am quite new to javascript/jquery so please don't judge my setTimeout-n00bidity to hard:
$( "#inputId" ).keydown(function (key){
var code = key.keyCode || key.which;
if( code == 32 ) { //Space key code
$( this ).val(
function( index, value ){
return value.substr( 0, value.length - 1 );
})
setTimeout(
function(){
$(this).val($(this).val() + "_");
}, 10
)
}
})
You may listen to the input event and then replace the spaces with underscores in the listener. This way, you don't need to have a timeout.
$("#inputId").on('input', function(key) {
var value = $(this).val();
$(this).val(value.replace(/ /g, '_'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="inputId">
No jQuery, simple solution:
var input = document.getElementById("inputId");
input.oninput = function (e) {
e.target.value = e.target.value.replace(' ', '_');
}
<input type="text" id="inputId" />
Use the keyup event rather than keydown, and simply replace all spaces with _. The keyup event runs after the value has been modified based on what the user typed, so you don't need to check the charCode.
$("#inputId").keyup(function() {
$(this).val(function(i, oldval) {
return oldval.replace(/ /g, '_');
});
});
You can use Change value of key board input
ex:
<div>
<label>Test:</label>
<input type="text" id="test">
</div>
$("#test").on("keypress", function (e) {
if (32 == e.keyCode) {
e.preventDefault();
var newString = $("#test").val() + "_";
$("#test").val(newString);
}
});
Related: jQuery: Change keyboard value when input
$( "#inputId" ).keyup(function (key){
var code = key.keyCode || key.which;
if( code == 32 ) { //Space key code
$(this).val($(this).val().replace(/ /g,"_"));
}
});

checking number or not when some text is pasted in a textbox (without set time out) [duplicate]

This question already has answers here:
Is it possible to get pasted text without using the setTimeout() function?
(4 answers)
Closed 8 years ago.
I have an input field like this
<input type ="number" id="numberTxt" placeholder="Number Only"/>
I am checking whether the value is a number or not and clearing back as the following function using keypress event
<script>
$(document).ready(function(numberTxt){
$('#numberTxt').keypress(function(event) {
var charCode = (event.which) ? event.which : event.keyCode;
if (charCode != 45 && (charCode != 46 || $(this).val().indexOf('.') != -1) && (charCode < 48 || charCode > 57))
{
return false;
}
else
return true;
});
});
</script>
BUT when we copy paste some text (CTRL V CNTRL C) the above code is
not working
or that i tried this function below
but not getting the value of the input at that point
its "" (empty string).
when we copy paste its correctly triggering this function.
<script>
$(document).ready(function(){
$('#numberTxt').on("paste",function('numberTxt') {
var val = $('#numberTxt').val() ;
});
});
</script>
Is the any another way to get the input tag's value with event ,
if i pass the event like the keypress function before
any other Suggestions or answers to check number during copy paste will also be helpful
One might well feel below function correct using .bind('input'.....
http://jsfiddle.net/pxfunc/KDLjf/ got this one from
Is it possible to get pasted text without using the setTimeout() function?
This is how you validate only integer value on PASTE
$('#numberTxt').on("paste",function(e) {
var $this = $(this);
setTimeout(function(){
var val = $this.val(),
regex = /^[\d]+$/;
if( regex.test(val) ){
$this.val( val );
}
else{
$this.val('');
}
alert(val);
},0);
});
DEMO: http://jsfiddle.net/jogesh_pi/LaN8f/1/

Categories

Resources