我使用CakePHP構建的應用程序中的幾個表單字段會爲它們的值收集百分比。我希望用戶能夠以熟悉的百分比(24.5%)格式查看和編輯百分比,但爲了簡化計算邏輯,我希望以十進制(.245)格式存儲它。由於有幾個這樣的字段,我寧願不必將每個百分比字段的轉換邏輯寫入控制器。自動轉換百分比輸入值
是否有人知道自動執行此轉換的簡單解決方案,還是我堅持編寫自定義幫助程序/行爲來解決此問題?
解決方案
我最後寫一個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 <[email protected]>
*/
(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();
這就是我最終做的。我在這個問題上發佈了這個實現。 –