Joe
Joe

Reputation: 425

Using jquery how do you auto fill commas in numeric form inputs?

I'm new to jquery and can't seem to figure out how to do this. Basically, when typing a large number into a form text field, I would like the commas to automatically be put in the field for the user without them having to type them in themselves. Could anyone help me figure this out?

Thanks.

Upvotes: 2

Views: 5656

Answers (4)

TheVillageIdiot
TheVillageIdiot

Reputation: 40497

You can use number formatter plugin

here are some examples from plug-in's page (link given above):

  // Brazilian currency format
  $(".numeric").number_format({precision: 2, decimal: ',', thousands: '.'});

  /* Results: number are formatted as they are typed
  123,45
  1.234,56*/
  // Changing precision to 5 decimal digits
  $(".numeric").number_format({precision: 5});

  /* Results: number are formatted as they are typed
  1,234.56789 
  0.12345 */

Upvotes: 2

daddywoodland
daddywoodland

Reputation: 1512

Use the blur event to reformat the number when the user leaves the text box.

$(".selector").blur(function() {
  $(this).val() = commafyValue($(this).val());
}

I nicked a commafy function from here but there's plenty to choose from or you can write your own...

function commafyValue(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

Upvotes: 0

Jonathan Kaufman
Jonathan Kaufman

Reputation: 314

Off the top of my head can't input fields have format masks on them. If not and someone had a gun to my head and said do this now, I would take the length of the cariable holding the number data and then divide it by 3, thne I know how many commas i need. Then using javascript use the substring method to grab each three from the right and place a comma before it.

Upvotes: 0

Christian C. Salvadó
Christian C. Salvadó

Reputation: 827246

I think you want to have a kind of masked input, check this plugin.

Upvotes: 3

Related Questions