在找到非常有用的建议和技巧后,我想出了这个片段。
我想检查表单字段是否已更改。如果为 true,则在页面顶部显示带有工具提示的警报图标,如果为 false 或返回字段默认值,则隐藏警报图标。使用这个脚本我可以完成它,但我想知道这是否是正确的方法以及是否可以改进。这里是新手:)
除了已经制作的内容之外,我还想标记已更改的字段(例如:更改字段标签类)。
$(':input').on('keyup keydown blur change', function () {
var isDirty = false;
$(':input').each(function () {
var $e = $(this);
if($e.is(':input[type=radio]') && $e.prop('defaultChecked') != $e.prop('checked')) {
isDirty = true;
} else if($e.is('select') && !this.options[this.selectedIndex].defaultSelected) {
isDirty = true;
} else if($e.is(':input[type=text], :input[type=url], :input[type=email], textarea') && $e.prop('defaultValue') != $e.val()) {
isDirty = true;
}
if(isDirty == true){
$("#toolbar-warning span").attr({
'class': 'btn active hasTooltip icon-warning-2',
'data-original-title': 'has changes!'
});
} else {
$("#toolbar-warning span").attr({
'class': 'btn hasTooltip icon-warning-2',
'data-original-title': ''
});
}
})
});
最佳答案
既然您已经使用了 jQuery,请尝试一下
1) 要检查表单是否已更改,请使用 .serialize():
var defaultForm = $unchangedForm.serialize();
function checkIfFormChanged($form) {
if(defaultForm !== $form.serialize())
return true;
else
return false;
// You can also use a one-liner: return !(defaultForm !== $form.serialize())
}
2) 要检查元素的默认值是否已更改,请在要检查的每个元素上添加一个change()选择器;
// This applies only to all the input elements
// Save the default values of elements in an array. Do this for every input element
var defaultValue[$myElem.attr('id')] = $myElem.val();
// more here
$('input').change(function(){
if(defaultValue[$(this).attr('id')] !== $(this).val()) // Value has changed
$(this).addClass('changedClass');
else
$(this).removeClass('changedClass');
});
关于jQuery 检查 HTML 表单是否已更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30548069/