Replacing comma with dot Char - javascript

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 + ".");
}
}
});

Related

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.

How to get keys pressed before enter with jQuery

Sorry if this question has already been asked, I am trying to create an app where the user scans a bar code and the data is then shown on the screen. I don't want to use textbox's because I don't want the data to be editable.
So far I've managed to get the enter key which is automatically sent at the end of the barcode but can't seem to get the keys pressed before, any help would be massively appreciated!
var item = "";
$(document).keypress(function(e) {
if(e.which == 13) {
alert(item);
}else{
item = item + e.which();
}
});
Just to clarify what I want to do is show an alert box with the keys pressed before enter! For example : A B C D ENTER would show an alert("ABCD")
Thanks!
UPDATE
So got my code to work but I'm getting "undefinedTHEKEYSPRESEDHERE" as the return:
var counter = 0;
var item = [];
$(document).keypress(function(e) {
if(e.which == 13) {
alert(item[counter]);
counter++;
}else{
item[counter] = item[counter] + String.fromCharCode(e.which);
}
});
Obviously this isn't clear enough, so I've outlined my problem below:
What I'm getting from alert(item[counter]);:
undefinedKEYS
What I want from alert(item[counter]);:
KEYS
So from undefinedKEYS to just KEYS I need to remove the text "undefined".
Clear enough?
Change e.which() to String.fromCharCode(e.which).
http://jsfiddle.net/8msksn3a/
var item = "";
$(document).keypress(function(e) {
if(e.which == 13) {
alert(item);
}else{
item = item + String.fromCharCode(e.which);
}
});
Not that I recommend this way of checking for previous results, but you are basically resetting item to "" inside the keypress event. Set it once outside the event.
which is a property, not a method:
Convert from ASCII to string char with string.fromCharCode (A google search would have given you that in two seconds).
Use (e.which || e.keyCode) to ensure you get the keycode on all browsers.
e.g.
var item = "";
$(document).keypress(function(e) {
if((e.which || e.keyCode) == 13) {
alert(item);
}else{
item = item + String.fromCharCode(e.which || e.keyCode);
}
});
Copy paste to your console and run:
var keys = [];
$(document).keypress(function(e) {
var keyChar;
if(e.which == 13) {
console.log( keys.join('') );
keys.length = 0;
}
else{
keyChar = String.fromCharCode(e.which);
if( keyChar )
keys.push( keyChar );
}
});
This technique will not show keys which does not have a textual character assigned to them (like the F1-F12 keys for example)

changing character code with js and show the new character instead

I want to write a code that if a user press a key, It changes the keyCode or charCode of the User event and trigger the event with a new charcode,
I wrote this code in jsfiddle but this code doesn't work because of too much recursion.
function convert(e, elem) {
function getKey(event) {
if (event.which == null) {
return event.keyCode // IE
} else if (event.which != 0 && event.charCode != 0) {
return event.which // the rest
} else {
return null // special key
}
}
var key = getKey(e);
key++;
return key;
}
$(".myInput").keypress(function (e) {
var returnedKey = convert(e, this);
e.which = e.keyCode = returnedKey;
$(this).trigger(e);
});
<input type="text" class="myInput" />
any Idea that help my code work would be appreciated.
Thanks alot.
Regarding the recursion issue, you need to add a stopping condition, for example:
$(".myInput").keypress(function (e) {
var returnedKey = convert(e, this);
e.which = e.keyCode = returnedKey;
if(!e.isSecondTrigger){
e.isSecondTrigger = true;
$(this).trigger(e);
}});
This way, you only change the value once. However, as was stated by LShetty in the comments section, the event values are read only - you can't change the value of the button that was already pressed and in that way change the input text. In order to do this, you need to manually change the value of the input text after each user action (i.e. hold the value of the input text at each key press, modify it when the user presses a key, and then overwrite the input field value with the output).

What jQuery event handler can be triggered after the deletion of all text in a form field?

If all of the text in a form field is selected and then the Backspace or Delete key are used, I want to be able to run some additional code. I have tried using change, blur, keypress, keydown. None seem to work.
Example that doesn't work:
$('input[id^=txtDate_]').on('keydown', function() {
enableSaveChanges();
});
Here is one way - http://jsfiddle.net/jayblanchard/6Uq85/
$('textarea[name="foo"]').keyup(function(e) {
var currentText = $(this).val();
if( 0 == currentText.length && (e.keyCode = 46 || e.keyCode == 8)) {
console.log('empty');
}
});
I should add that I am a fan of keyup() here as the event order for keypress,keydown and keyup are different. You can test to see which makes more sense for you. The reason that I use keyup here is because the textarea (or input) isn't actually empty when you press the key.
Use the key codes for 'delete' and 'backspace'
delete = 46
backspace = 8
example:
HTML:
<input type="text" id="input">
jQuery:
jQuery('#input').keyup(function(e) {
var str = jQuery('#input').val();
if( (e.keyCode == 46 || e.keyCode == 8) && str == "" ) {
alert("Hey");
}
});
EDITED: check for empty input field
Try this way for
<input type="txt" id="txt"/>
$('#test').keyup(function(e){
if($('#test').val() == '' && e.keyCode == 46 || e.keyCode == 8)){
console.log('Input is emptied');
}
});

Categories