tags:

views:

682

answers:

4

Hello guys,

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.

+2  A: 

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

CMS
Very cool plugin!
fudgey
A: 

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.

Jonathan Kaufman
A: 

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;
}
daddywoodland
+1  A: 

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 */
TheVillageIdiot