我使用 CakePHP 构建的应用程序中的几个表单字段收集其值的百分比。我希望用户能够以熟悉的百分比 (24.5%) 格式查看和编辑百分比,但我想以十进制 (.245) 格式存储它,以便简化计算逻辑。由于存在多个此类字段,因此我不想将转换逻辑写入每个百分比字段的 Controller 中。
有谁知道自动执行此转换的简单解决方案,或者我是否一直在编写自定义帮助器/行为来解决此问题?
解决方案
我最终编写了一个 jQuery 插件来处理这个问题。在这里,对于将来可能需要它的任何人:
/**
* 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 <<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a5cecac6cdc7e5c4c0c1ccd6ccd18bc6cac8" rel="noreferrer noopener nofollow">[email protected]</a>>
*/
(function($) {
$.fn.inputPercent = function() {
return this.each(function() {
var display_field = this;
var value_field = $('<input type="hidden" />').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);
用法:
$('input.percent').inputPercent();
最佳答案
您可以编写一些简单的 javascript(使用您最喜欢的框架或纯 js)来在提交之前转换具有 #percentage 类的字段。
或者,也可以不用 javascript 来处理用户;在模型中,添加 beforeSave() 方法,检查数字是否 < 1,如果不是,则除以 100。
如果 NumberHelper 无法提供帮助,您还可以添加一个简单的组件或帮助程序,将内部数字转换回百分比以供显示。
关于php - 自动转换百分比输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7560825/