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)
str.gsub!(/[^0-9.]/,'')
end
def fmt_dollar(fld)
"$ " + fld.to_s.reverse.gsub(/...(?=.)/,'\&,').reverse
end
def formatted_field_needing_hint
fmt_dollar(field_needing_hint)
end
def formatted_field_needing_hint=(str)
self.field_needing_hint = cvt_dollar(str)
end
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,'');
if(isNaN(num))
num = "0";
sign = (num == (num = Math.abs(num)));
num = Math.floor(num*100+0.50000000001);
cents = num%100;
num = Math.floor(num/100).toString();
if(cents<10)
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))+','+
num.substring(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);"
end
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.