Đây là một giải pháp thanh lịch.
Có thuộc tính ẩn cho mỗi phần tử đầu vào trên biểu mẫu mà bạn có thể sử dụng để xác định xem giá trị có bị thay đổi hay không. Mỗi loại đầu vào có tên thuộc tính riêng. Ví dụ
- cho
text/textarea
nó là defaultValue
- vì
select
nó mặc định Chọn
- cho
checkbox/radio
nó defaultChecked
Đây là ví dụ.
function bindFormChange($form) {
function touchButtons() {
var
changed_objects = [],
$observable_buttons = $form.find('input[type="submit"], button[type="submit"], button[data-object="reset-form"]');
changed_objects = $('input:text, input:checkbox, input:radio, textarea, select', $form).map(function () {
var
$input = $(this),
changed = false;
if ($input.is('input:text') || $input.is('textarea') ) {
changed = (($input).prop('defaultValue') != $input.val());
}
if (!changed && $input.is('select') ) {
changed = !$('option:selected', $input).prop('defaultSelected');
}
if (!changed && $input.is('input:checkbox') || $input.is('input:radio') ) {
changed = (($input).prop('defaultChecked') != $input.is(':checked'));
}
if (changed) {
return $input.attr('id');
}
}).toArray();
if (changed_objects.length) {
$observable_buttons.removeAttr('disabled')
} else {
$observable_buttons.attr('disabled', 'disabled');
}
};
touchButtons();
$('input, textarea, select', $form).each(function () {
var $input = $(this);
$input.on('keyup change', function () {
touchButtons();
});
});
};
Bây giờ chỉ cần lặp qua các biểu mẫu trên trang và bạn sẽ thấy các nút gửi bị tắt theo mặc định và chúng sẽ CHỈ được kích hoạt nếu bạn thực sự thay đổi một số giá trị đầu vào trên biểu mẫu.
$('form').each(function () {
bindFormChange($(this));
});
Triển khai dưới dạng jQuery
plugin tại đây https://github.com/kulbida/jmodifiable