Automatically convert percentage input values

Several of the form fields in an application I am building using CakePHP collect percentages for their values. I would like the users to be to see and edit percentages in the familiar percentage (24.5%) format, but I want to store it in decimal (.245) format in order to ease calculation logic. Since there's several of these fields, I'd rather not have to write the conversion logic into the controllers for every single percentage field. Is anyone aware of a simple solution to automatically performing this conversion, or am I stuck writing a custom helper/behavior to solve this problem? **Solution** I ended up writing a jQuery plugin that handles this. Here it is, for anyone who might need it in the future: /** * Input Percent * * Percentages are tricky to input because users like seeing them as 24.5%, but * when using them in calculation their value is actually .245. This plugin * takes a supplied field and automatically creates a percentage input. * * It works by taking an input element and creating a hidden input with the same * name immediately following it in the DOM. This has the effect of submitting * the proper value instead of the human only one. An onchange method is then * bound to the original input in order to keep the two synced. * * Potential Caveats: * * There will be two inputs with the same name. Make sure anything you * script against this field is prepared to handle that. * * @author Brad Koch */ (function($) {   $.fn.inputPercent = function() {     return this.each(function() { var display_field = this; var value_field = $('').get(0); // Initialize and attach the hidden input. $(value_field).attr('name', $(this).attr('name')); $(value_field).val($(display_field).val()); $(display_field).after(value_field); $(display_field).after('%'); // Convert the display field's proper percent value into the display format. if (isFinite($(display_field).val())) { $(display_field).val($(display_field).val() * 100); } // Enable synchronization between the two. $(this).bind('change', function () { var value = $(display_field).val(); // Handle non-numeric values. if (isFinite(value)) { $(value_field).val(value / 100); } else { $(value_field).val(value); } });     }); }; })(jQuery); Usage: $('input.percent').inputPercent();

以上就是Automatically convert percentage input values的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏