How to format currency while typing, but you also want to use that input as a number after formatting (jQuery/Javascript) - javascript

I am trying to build an online calculator and I wanted to format my input into currency while typing.
On this website: https://www.ratehub.ca/cmhc-mortgage-insurance the asking price input box is similar to what I would like to achieve.
I have tried this code here:
$("#formattedNumberField").on('keyup', function(){
var n = parseInt($(this).val().replace(/\D/g,''),10);
$(this).val(n.toLocaleString());
//do something else as per updated question
myFunc(); //call another function too
});
But it would display NaN after typing a number and deleting it, also I can not use the formatted number for future calculation.
Any help would be appreciated!

Related

How do I get this script to multiply a number that was typed into the input field?

I'm trying to pull the number that a user types into a text field and multiply that by a number that is already established. (There are other buttons that add +1 or subtract -1 from the total that work just fine. The only problem I'm having is this right here, getting a user's input by them typing in a value to a field and pulling it)
Here's my code:
<!-- HTML Field that I am trying to pull a number out of -->
<input type="text" id="multNumInput">
--
// Creative my variables
var number = 0;
// Creative a variable that is equal to whatever is inputted into the text box
var multNum = $("#multNumInput").val();
// On Button Click, take the number variable and multiply it times whatever the value was inputted in the html
$('#multiply').click(function(){
number = number * multNum;
$('result1').text(number);
console.log(number);
})
Hopefully this is clear enough to understand. As of right now, whenever I click the button, it always changes the number back to 0. That's it. Just 0. No matter what I set the num var to, when clicking the mult button, it always reverts to 0.
You have to convert to number first.
multNum = parseInt(multNum);
number = number * multNum;
//...
First of all, the obvious: Multiplying any number with your number variable which has 0 value will lead to 0 at all times - I suppose you know this but was confused or missed that part, probably by confusing it to initialization of 0 before an addition process. Set it to 1 or another non-negative number and you will probably get better results on the way. :)
In addition, to make it multiply correctly in JS, you have to multiply between two numbers.
Your value is of type String as inserted in your input field.
As already suggested by #Si8, you need to parse it to Number by doing:
multNum = parseInt(multNum);
Also, you seem to be using a text type for your input.
I suggest you set it to a number type, so that you restrict input values:
<input type="number" id="multNumInput">
Check out the Mozilla MDN web docs for more on this.
The answer, as provided by #Robin Zigmond in a comment is this:
"You're failing to convert multNum from a string to a number."

What is the best way to make a prompt into an integer in JS? [duplicate]

This question already has answers here:
How to get numeric value from a prompt box? [duplicate]
(6 answers)
Closed 9 months ago.
I am writing a program to perform "Russian Math" (using the numberphile youtube video on it as my basis for the algorithm). It works. But, to "prove" that it works, I'm giving the user the ability to try using their own numbers as input.
When I assign numbers to the variables myself, it works without fail. However, when I use prompt var numberOne = prompt('What is the first number you want to multiply?'); on one variable (with the other being assigned myself)it works. But as soon as I prompt the user for both numbers it won't work. Presumably because a string can be converted to an integer when an operation is performed on it (multiplied by an integer), but it does not seem to work when both are strings.
Adding another line to reset the prompt variable to an integer using parse seems like too much extra.
var numberOne = prompt('What is the first number you want to multiply?');
var numberTwo = prompt('What is the second number you want to multiply?');
var numberOneInt = parseInt(numberOne);
var numberTwoInt = parseInt(numberTwo);
Is this really the best way to do it?
For a prompt, yes, that is pretty much what you want to do. Prompt returns a string, so you need to convert it. There are other ways, i.e. Number(numberOne), but parseInt is fine. They have slightly different behaviors, but for your case they're mostly the same. (parseInt stops parsing at the first non-number, while Number type-casting attempts to convert the whole thing).
And kudos for figuring out the edge behavior of having one string and one int multiplied together.
In general, most developers prefer using inputs on the page rather than prompts. The problem with prompts is that they interrupt the user's control of the page. As a bonus, with inputs you can set type=number to give the users number controls on some devices and limit the input to actual numbers.
Edit
I don't ever use prompt, so I was reading up on them. One thing to look out for is if the user hits escape, it returns null, which may break your code. You could prevent that by just checking for it first, i.e. if(numberOne){ ... }

Function not calculating values of formatted numbers

I built a calculator that takes user input (1 text field, 2 select dropdowns) and then displays the output below if the required conditions are met. I also wanted to have the text input field display thousand separators (commas) dynamically as the user types in a number, which I achieved using this:
$('#orderAmt').keyup(function(event) {
// skip for arrow keys
if (event.which >= 37 && event.which <= 40) return;
// format number
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
});
});
Now, as expected, the calculator function doesn't recognize any of these values because they have been converted to strings. I assume that the next step is to use something like parseInt, so I added this line at the end of the .keyup function:
var converted = parseInt($('#orderAmt'), 10);
But I'm lost on what to do next, because the actual calculator function is written in vanilla JS and here I am trying to store the user's value in a new jQuery variable. Is there a better approach that I should be taking with this?
Here's my JSFiddle - https://jsfiddle.net/bkroger7/yk13wzcc/
If anyone can point me in the right direction it would be greatly appreciated.
BTW - I've tried the infamous, non-jQuery addCommas function as seen here but it won't work for me - only jQuery-based solutions have been working so far.
your problem is you are adding commas to the input field and then taking it as is...
so when you use $('#orderAmt').val() after you add commas you will get 3,000 instead of 3000
what you need to do is just remove the commas...
here is a working fork
https://jsfiddle.net/Lw9cvzn0/1/
notice: var orderAmount = $('#orderAmt').val().replace(new RegExp(','), '');
You're missing the call to .val() to get the field's value. And then you have to remove the commas before you parse it.
var converted = parseInt($('#orderAmt').val().replace(/,/g, ''), 10);

formatcurrency Phonegap

Team, I'm trying to format a string of characters into Italian Currency format - say something like €1.230,32 from the api documentation i understand it can be achieved through Worklight - Corodova. But I'm not able to land in a clear - cut example as to how. Can you help ?
Your question is not very clear to me.
If what you actually want to do is to convert a sum of money from one currency to another, you can check the following:
http://docs.phonegap.com/en/2.2.0/cordova_globalization_globalization.md.html
https://github.com/apache/cordova-plugin-globalization/blob/master/docs/globalization.getCurrencyPattern.md
http://pic.dhe.ibm.com/infocenter/wrklight/v6r0m0/index.jsp?topic=%2Fcom.ibm.worklight.help.doc%2Fdev%2Fc_globalization_in_ibm_worklight.html
http://www.sitepoint.com/build-a-currency-converter-with-jquery-mobile-and-cordova-part-4/

Dynamic Smart date mask while inserting date

Is there a way in javascript or jQuery to detect and change dynamically while typing a date for both a key input and a copy and paste to a text box?
I'm trying to create a functional text box which has two digits such as a month.
Since the month can be a number from 1 - 12 I want to enforce the first digit to be a 1 or a 0.
The trick that I'm trying to do however is when the text box first gains focus and a user beging to type a number, if that number is 2 - 9 I want a zero to automatically fill the first spot and then but the 9 in the second spot.
Before I type anything this date input would look like so:
__/__/_____
If I type a "1"
1_/__/_____
If I type "2" should get
02/__/_____
If I type "22" should get
02/2_/_____
If I type "77" should get
07/07/_____
I would be very interested for in an answer with code or a link to a tool that already does this or a link to a previous post?
Eventually I want to put it in a masked so 7/7/2011 or 7/7/11 or 07/07/2011 will alway fill to 07/07/2011. In the final final version I am trying to get the year to default to the current decade but have a drop down to each 10 year++ --.
Why not attach a listener to the blur of the textbox, rather than to the user's typing.
Think about the user experience if you were typing "1", and all of a sudden, the input started adding or removing zeroes to what you were doing, while you were doing it?
var dayInput = document.getElementById("day-input");
// usually, I'd just use event-listeners, but feel free to refactor
dayInput.onblur = handleDayOrMonth;
function handleDayOrMonth () {
var el = (this === window) ? event.srcElement : this,
number_string = el.value;
// checking that it's an actual number
if (!isNaN(parseInt(number_string)) {
if (number_string.length === 1) { el.value = "0" + number_string; }
}
}
Handling the year would be just the same, except that you'd be adding "20" to the start of whatever it is.
Feel free to jQuery it up.
I believe that the functionality that you want is provided by the jQuery Masked Input plugin
Demo: http://jsfiddle.net/SO_AMK/SEXAj/
Please note that it also only allows numeric characters.
Answer goes here... jQuery masked input plugin.

Categories

Resources