Несколько полей формы в приложении, которое я создаю с помощью 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 <kochb@aedisit.com>
*/
(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();