I need to add formatting to my inputBox suited for currency, it should look like this: £000,000.000.
This what my script currently looks like:
var elDeliveryPrice = document.getElementById('deliveryPrice');
var elOrderValue = document.getElementById('orderValue');
var formatter = new Intl.NumberFormat('gb-GB', { style: 'currency', currency: 'GBP' });
elOrderValue.addEventListener('keyup', _ => {
let curVal = elOrderValue.value;
let curValFloat = parseFloat(curVal);
if (isNaN(curValFloat)) {
elDeliveryPrice.innerHTML = '';
return;
}
elDeliveryPrice.innerHTML = formatter.format((curValFloat * 0.025) + 4);
});
Here's what the elements look like. Check out what it looks like on the live site. This script currently shows the inputted number value on keyup with an added formula to show a price that's relative to the input value on a separate div block, with currency formatting only on the output. How would I modify this code to add formatting to the inputBox whilst a user is typing? Thanks.
I'm not an UX expert, but from my experiences I can tell you you shouldn't do it as long as the cursor is inside the textfield. Formatting the input while the user is still typing creates a lot of frustration and "weird" behaviour for the user (jumping cursor, suddenly special characters appear, etc.). Maybe it's fine to format it back and forth when the input gains and looses focus.
However, to do it regardless what people think about your page and it's usability: Assign the formatted text to the value property of the input:
var elDeliveryPrice = document.getElementById('deliveryPrice');
var elOrderValue = document.getElementById('orderValue');
var formatter = new Intl.NumberFormat('gb-GB', { style: 'currency', currency: 'GBP' });
elOrderValue.addEventListener('keyup', _ => {
let curVal = elOrderValue.value;
let curValFloat = parseFloat(curVal);
if (isNaN(curValFloat)) {
elDeliveryPrice.innerHTML = '';
return;
}
elOrderValue.value = formatter.format((curValFloat * 0.025) + 4); // <-- this line
});
Be warned: It will most certainly result in bugs/strange behaviour/whatever.
Related
I am a beginner and I have an if statement that is returning the input value in the text box that I want the calculation to be in, and returning the calculation in the text box where I originally input the information.
diagram of problem
$w.onReady(function () {
$w("#generatequote").onClick((event) => {
var SR = Number($w("#SR").value);
if (SR<100) {
$w("#SR").value = SR*2
//if the input number is less than 100 display the input number times two
}
$w("#quotetext").value =(SR)
});
This is a different way I tried but then it displays the input value without making the calculation
var SR = Number($w("#SR").value);
if (SR<100) {
$w("#SR").value = ("#SR")*2
This is another way I tried but it also doesn't make the calculation
var SR = Number($w("#SR").value);
if (SR<100) {
$w("#SR").value *2
}
Just a guess, the only problem with your first code seems to be that you mixed up the two text-boxes.
"#SR" is the input box, and you are giving it a value of SR*2.
$w("#SR").value = SR*2
While "#quotetext" is where you want to display the result, but you are giving it a value of SR.
$w("#quotetext").value =(SR)
So, try flipping it around?
$w.onReady(function () {
$w("#generatequote").onClick((event) => {
var SR = Number($w("#SR").value);
if (SR<100) {
$w("#quotetext").value = SR*2
//if the input number is less than 100 display the input number times two
}
$w("#SR").value =(SR)
});
I have a text field with type='text' and I am trying to format the text with commas. Example: 500000000 would become 500,000,000.
I have the following code:
function addComma(values) {
values.value = values.value.replace(",", "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
if (document.getElementById("values"))
payment = parseInt(document.getElementById("values").value);
<label1>Rent</label1> <input id="values" type="text" onkeyup="addComma(this);">
However, it's printing 5,000,0,0,0,000 and the formatting is off for some reason. I also tried .toLocaleString(), but that doesn't seem to work either. What am I doing wrong here?
I was referred to a few other posts on Stack Overflow, but nothing seems to work out.
function addComma(values) {
const v = values.value && new Number(values.value.replace(/,/g,''));
values.value = v.toLocaleString();
}
if (document.getElementById("values"))
payment = parseInt(document.getElementById("values").value);
<label1>Rent</label1> <input id="values" type="text" onkeyup="addComma(this);">
You can do this by converting the number to a string, then manually iterating over each character and find places where a comma is needed.
function formatNumber(number) {
var str = number.toString();
var offset = str.length % 3;
var newStr = '';
for (var i = 0; i < str.length; i++) {
if (i > 0 && i % 3 === offset) {
newStr += ',';
}
newStr += str[i];
}
console.log(str, '=>', newStr);
}
formatNumber(5);
formatNumber(50);
formatNumber(500);
formatNumber(5000);
formatNumber(50000);
formatNumber(500000);
formatNumber(5000000);
I'd recommend using a change event rather than a keyup event as change will only update the value when the input is no longer the focus. If you use keyup the code will try and reinterpret the new string you add back to the input as a number and throw an error.
Here's the code using toLocaleString (just press tab after adding the number as if to move to the next input box):
const values = document.querySelector('#values');
values.addEventListener('change', handleChange, false);
function handleChange(e) {
const value = Number(e.target.value);
const formatted = value.toLocaleString();
values.value = formatted;
}
<input id="values" type="text">
The other answers posted before this one using the input field are ok to show how it works, but they are bugged as soon as you enter a new number when it has formatted to a string using toLocaleString(). For that reason I added the toNumber() function to be complete. In the example below I preform the following steps:
When user fills in a number in the input field and leaves the input field: Call toString(e) and make from the entered number a formatted string.
If the user again selects the input field, call toNumber(e) and format it back to a number.
This makes sure you won't get NaN when reselecting or will become completely unusable.
The NaN property represents "Not-a-Number" value. This property indicates that a value is not a legal number.
It is still possible to add text in it, this will result in NaN as text cannot be formatted to a number. This could be filtered out in the toString(e) when necessary. I did this in the example below by adding if (formatted !== 'NaN') {} Only when it's not NaN it will set the value to the new formatted number. Else it won't do anything. Please note: a number with dots is a string in this case so wont work either.
const values = document.querySelector('#values');
values.addEventListener('click', toNumber, false);
values.addEventListener('focusout', toString, false);
function toNumber(e) {
const value = e.target.value;
const unformatted = value.replace(/\D/g,'');
values.value = unformatted;
}
function toString(e) {
const value = Number(e.target.value);
const formatted = value.toLocaleString();
if (formatted !== 'NaN') {
values.value = formatted;
}
}
<input id="values" type="text">
To fix that, you can also remove my addition and add a filter before the toString(e) does it's thing and filter the dots, text etc. so only the numbers remain.
I have an app which is mostly about studying a new language. In my application there is an input field which expects text in a language that user study.
So if user focuses on that input, ideally, I want automatically to switch a layout to a target language. To make user experience more enjoyable (you don't need to worry about a wrong layout).
What I know and have tried
As I know browsers not able to provide API which I can use to determine a current layout.
I have tried to detect if the last entered character is not a typical character for the target language then I use my mapping between key codes and target language letters and replace that entered character in particular position in input. After that I get caret reset. So I return it to previous position.
The problem with the second approach that if you type fast enough you can encounter problems with a caret position. And it leads to a wrong string in the input.
Do you have any ideas how to achieve that behavior which works even when you type text with a speed when you almost immediately press two keys at the same time?
P.S. Code for that described approach
const codeToEn = {
65: 'a',
// ... and so on
}
const acceptableChars = /^[a-zA-Z0-9 .+_)(%#!?,&$*'"`~]+$/g;
document.getElementById('some-input-id').addEventListener('keyup', function (e) {
if (codeToEn[e.which]
&& !acceptableChars.test(this.value)) {
const char = codeToEn[e.which];
const {selectionStart, selectionEnd} = this;
const currentVal = this.value;
let leftPart = currentVal.substring(0, selectionStart - 1);
let rightPart = currentVal.substring(selectionStart );
this.value = leftPart + char + rightPart;
this.setSelectionRange(selectionStart, selectionEnd);
}
});
Convert Layout will help you:
https://github.com/ai/convert-layout
It really small and supports many languages.
Before you look into the code below, please note that my solution assumes that all the users use QWERTY / ЙЦУКЕН keyboard layout. This may be a huge simplification and you'll have to find a more complex approach to the keyboard layout detection (generally it's all about finding a correct symbols mapping).
The more useful part here is a fast substitution of symbols. So type fast or even copy-paste text. Hope it helps!
const En = "qwertyuiop[]asdfghjkl;'zxcvbnm,.",
Ru = "йцукенгшщзхъфывапролджэячсмитьбю";
const RuEn = [...Ru].reduce((a, e, i) => (a[e] = En[i]) && (a[e.toUpperCase()] = En[i].toUpperCase()) && a, {});
let corrected = 0;
document.getElementById('ta').addEventListener('input', function() {
let end = this.selectionEnd;
for (let i = !!corrected * (this.value.length - corrected - 1); i < end; i++) {
let s = RuEn[this.value[i]];
if (s) this.value = this.value.split(this.value[i]).join(s);
}
this.selectionEnd = end;
corrected = this.value.length - 1;
});
<textarea id="ta" cols="50" rows="10"></textarea>
I would like to find difference between two fields using JavaScript in iText.
I am able to find the sum of them using below code:
PdfStamper stamperResult = new PdfStamper(readersectionResult, new FileOutputStream(RESULT_NEW));
stamperResult .addJavaScript("var nameField = this.getField(\"total\");"+ "nameField.setAction(\"Calculate\",'AFSimple_Calculate(\"SUM\",\"total1\", \"total2\")')");
Is there any way to find the difference using 'AFSimple_Calculate' similar to what I did in the above code snippet?
Thanks for editing! I tried your suggestion but it does not seem to work for some reason.
stamperResult.addJavaScript(" var total1 = this.getField(\"value1\"); var total2 = this.getField (\"value2\"); var subtr = this.getField(\"total\"); subtr.value = total1.value - total2.value;");
I separated newlines by spaces and added right escape characters.
I was also thinking of using a different logic for subtraction using AF methods : like this
stamperResult.addJavaScript("var nameField = this.getField(\"total\");"+ "nameField.setAction(\"Calculate\",'AFSimple_Calculate(\"SUM\",\"total1\", \"-total2\")')");
In the above code I was trying to add -(negative value) to total 2 so that it will be subtracted from total1 though the AF method is still 'SUM'.
But that does not work.
The below simple code seem to work :
stamperResult.addJavaScript("var nameField = this.getField('total');" +
"nameField.setAction('Calculate'," +
"'subtract()');" +
"" +"function subtract(){this.getField('total').value
= (this.getField('total_1').value -this.getField('total_2').value); }");
I updated your question because it contained many spelling errors. I didn't edit the code snippet because I don't know what the original code snippet is like. In any case: I think something went wrong during the copy/paste process, as I don't think your code snippet compiles in its current state.
In any case: as far as I know the AF-methods (the AF stands for Adobe Forms) may not be present in every viewer, and as far as I know Adobe didn't implement a way to subtract values from each other in the AFSimple_Calculate method.
For these two reasons, you may prefer regular JavaScript instead of using a pre-canned function that may or may not be pre-canned.
This regular JavaScript may look like this:
var total1 = this.getField("total1");
var total2 = this.getField("total2");
var subtr = this.getField("difference");
subtr.value = total1.value - total2.value;
I'm not sure if that answers your question. Maybe you just want:
var total1 = this.getField("total1");
var total2 = this.getField("total2");
var namefield = total1.value - total2.value;
You can put these lines inside a String using the right escape characters and replacing the newlines by spaces or newline characters.
Of course, you need to trigger this code somewhere. Below you'll find an example that puts the negative value of the content of a value1 field into a value2 field.
public static void main(String[] args) throws IOException, DocumentException {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("js.pdf"));
document.open();
writer.addJavaScript("function makeNegative() { this.getField('value2').value = -(this.getField('value1').value); } ");
Rectangle rect1 = new Rectangle(40, 740, 200, 756);
TextField value = new TextField(writer, rect1, "value1");
value.setBorderColor(GrayColor.GRAYBLACK);
value.setBorderWidth(0.5f);
PdfFormField field = value.getTextField();
field.setAdditionalActions(PdfName.BL, PdfAction.javaScript("makeNegative();", writer));
writer.addAnnotation(field);
Rectangle rect2 = new Rectangle(40, 710, 200, 726);
TextField neg = new TextField(writer, rect2, "value2");
neg.setBorderColor(GrayColor.GRAYBLACK);
neg.setBorderWidth(0.5f);
writer.addAnnotation(neg.getTextField());
document.close();
}
Note that I used a Blur action. This means the method will be triggered as soon as you select another field after filling out the value1 field.
I'm struggling with a ExtJS 4.1.1 grid that has editable cells (CellEditing plugin).
A person should be able to type a mathematic formula into the cell and it should generate the result into the field's value. For example: If a user types (320*10)/4 the return should be 800. Or similar if the user types (320m*10cm)/4 the function should strip the non-mathematical characters from the formula and then calculate it.
I was looking to replace (or match) with a RegExp, but I cannot seem to get it to work. It keeps returning NaN and when I do console.log(e.value); it returns only the originalValue and not the value that I need.
I don't have much code to attach:
onGridValidateEdit : function(editor,e,opts) {
var str = e.value.toString();
console.log(str);
var strCalc = str.match(/0-9+-*\/()/g);
console.log(strCalc);
var numCalc = Number(eval(strCalc));
console.log(numCalc);
return numCalc;
},
Which returns: str=321 strCalc=null numCalc=0 when I type 321*2.
Any help appreciated,
GR.
Update:
Based on input by Paul Schroeder, I created this:
onGridValidateEdit : function(editor,e,opts) {
var str = e.record.get(e.field).toString();
var strCalc = str.replace(/[^0-9+*-/()]/g, "");
var numCalc = Number(eval(strCalc));
console.log(typeof numCalc);
console.log(numCalc);
return numCalc;
},
Which calculates the number, but I am unable to print it back to the grid itself. It shows up as "NaN" even though in console it shows typeof=number and value=800.
Final code:
Here's the final code that worked:
onGridValidateEdit : function(editor,e,opts) {
var fldName = e.field;
var str = e.record.get(fldName).toString();
var strCalc = str.replace(/[^0-9+*-/()]/g, "");
var numCalc = Number(eval(strCalc));
e.record.set(fldName,numCalc);
},
Lets break this code down.
onGridValidateEdit : function(editor,e,opts) {
var str = e.value.toString();
What listener is this code being used in? This is very important for us to know, here's how I set up my listeners in the plugin:
listeners: {
edit: function(editor, e){
var record = e.record;
var str = record.get("your data_index of the value");
}
}
Setting it up this way works for me, So lets move on to:
var strCalc = str.match(/0-9+-*\/()/g);
console.log(strCalc);
at which point strCalc=null, this is also correct. str.match returns null because your regex does not match anything in the string. What I think you want to do instead is this:
var strCalc = str.replace(/[^0-9+*-]/g, "");
console.log(strCalc);
This changes it to replace all characters in the string that aren't your equation operators and numbers. After that I think it should work for whole numbers. I think that you may actually want decimal numbers too, but I can't think of the regex for that off the top of my head (the . needs to be escaped somehow), but it should be simple enough to find in a google search.