Topic: how to use Rails NumberHelper methods on client-side?


I'd like to very strongly hint at the acceptable format of some of my textfields by 'prepopulating' them with indicative characters when the user enters the fields. So, with some effort I could devise javascripts that populate textfields with '%' or currency signs or separate digits with commas. Yet, these are all things that Rails' NumberHelper will do on the server-side. Ideally, I could just call those utilities on the client-side. Any suggestions on how to do this or otherwise accomplish my task using existing resources?



Re: how to use Rails NumberHelper methods on client-side?

There is no real straightforward direct way to leverage rails format helpers on the browser/java script side.   

One approach, define formatted versions of your attributes that need indicative defaults, i.e. in your model which contains an attributed named 'field_needing_hint',  assume you want to indicate a dollar amount be entered:

def cvt_dollar(str)
def fmt_dollar(fld) 
  "$ " + fld.to_s.reverse.gsub(/...(?=.)/,'\&,').reverse
def  formatted_field_needing_hint
def formatted_field_needing_hint=(str)
  self.field_needing_hint = cvt_dollar(str)

I also use an onblur event handler on the client side to enforce a proper dollar format, i.e.:

formatDollar = function(num) {
  num = num.toString().replace(/\$|\,/g,'');
    num = "0";
  sign = (num == (num = Math.abs(num)));
  num = Math.floor(num*100+0.50000000001);
  cents = num%100;
  num = Math.floor(num/100).toString();
    cents = "0" + cents;
  for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    num = num.substring(0,num.length-(4*i+3))+','+
  return (((sign)?'':'-') + '$ ' + num );

That's just some random JavaScript formatting code, use whatever you like,  then in my views:

form_for @thing  do |f|
    text_field :formatted_field_needing_hint , :onblur=>"this.value=formatDollar(this.value);"

So if field_needing_hint is nil or contains "0",  the user will be prompted with "$ 0" as the default value.

Last edited by BradHodges (2010-05-04 13:34:49)

Joe got a job, on the day shift, at the Utility Muffin Research Kitchen, arrogantly twisting the sterile canvas snout of a fully charged icing anointment utensil.

Re: how to use Rails NumberHelper methods on client-side?


Thanks! Your response marks one of the most complete I've seen, much less enjoyed direct use of.

Thanks again,