我有一个包含多个输入字段、文本区域、单选按钮和复选框的表单。一旦任何字段中的值发生更改,我应该将带有字段名称、旧 和新值的 ajax 发送到我的服务器。我该怎么做?
更新。这是当前的方法:
oldValueHolder = null;
$('input[type="text"]').focus(function() {
oldValueHolder = this.value;
});
$('input[type="text"]').focusout(function() {
if (this.value != oldValueHolder) alert(this.name + ': ' + oldValueHolder + ' -> ' + this.value);
});
$('input[type="checkbox"]').click(function(event) {
alert(this.name + ': ' + !$(event.target).is(":checked") + ' -> ' + $(event.target).is(":checked"));
});
但我仍然不清楚如何用单选按钮做同样的事情。
Upd2. 下面是单选按钮的解决方案:
$('input[type="radio"]').change(function() {
alert(this.name + ': ' + $(this).parents("div.control-group").attr('data-original-value') + ' -> ' + this.value);
$(this).parents("div.control-group").attr('data-original-value', this.value);
});
最佳答案
您需要在旧值更改之前捕获它。一种方法是:
- 当一个对象获得焦点时,在一个临时变量中获取它的值。
- 如果对象值发生变化,将新值和旧值通过ajax发送。
这样做的优势是您没有加载具有所有值的整个数组,您只是得到一个具有最后一个值的滚动临时变量获得焦点的对象。更少的内存使用。
更新: 使用 jQuery 将函数绑定(bind)到类“myClass”的所有输入上的焦点事件,例如:
HTML:
<input class="myClass" type="text" />
JS:
myUniversalOldValueHolder = null; // notice this is globally scoped.
$(".myClass").focus(function() {
myUniversalOldValueHolder = this.value; // "this" is the <input> element, in this context
});
...并使用 $(".myClass").change()
来定义元素更改时要执行的操作。
jQuery 焦点():http://api.jquery.com/focus/
jQuery 更改():http://api.jquery.com/change/
关于javascript - 任何字段更改时如何发送新值和旧值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9315777/