Bill Kroger
Bill Kroger

Reputation: 55

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.

Upvotes: 1

Views: 46

Answers (2)

WalksAway
WalksAway

Reputation: 2819

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(','), '');

Upvotes: 1

Barmar
Barmar

Reputation: 781059

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

Upvotes: 1

Related Questions