我使用了引用Generic way to detect if html form is edited
中的代码$.fn.extend({
trackChanges: function () {
$(":input", this).change(function () {
$(this.form).data("changed", true);
});
},
isChanged: function () {
return this.data("changed");
}
});
并使用它
$("#check").click(function () {
$("#myform").trackChanges();
if ($("#myform").isChanged()) {
alert("changed");
} else {
alert("Not changed");
}
});
但是我不明白如何捕捉未改变的事件,每当我点击按钮它发出警报改变时,我也需要捕捉未改变的事件。控制不会转向其他部分
HTML
<form id="myform">
<input type="text" id="id1" />
<select id="id2" ><option>1</option><option>2</option></select>
<textarea>asdasd</textarea>
<input type="button" id="check" value="button"/>
</form>
$.fn.extend({
trackChanges: function () {
$(":input", this).change(function () {
$(this.form).data("changed", true);
});
},
isChanged: function () {
return this.data("changed");
}
});
&#13;
<form id="myform">
<input type="text" id="id1" />
<select id="id2"><option>1</option><option>2</option></select>
<textarea>asdasd</textarea>
<input type="button" id="check" value="button" />
</form>
<script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
<script>
$(document).ready(function () {
$("#myform").trackChanges();
$("#check").click(function () {
if ($("#myform").isChanged()) {
alert("vam");
} else {
alert("no");
}
});
});
</script>
&#13;
答案 0 :(得分:0)
请查看此内容
function check() {
$("#myform").trackChanges();
if ($("#myform").isChanged()) {
alert("changed");
//set flag to false again
setData();
} else {
alert("Not changed");
}
}
function setData() {
var f = $('#myform'),
inps = f.find(":input").not(":input[type=button]").toArray();
f.data("changed", false);
$.each(inps, function(i, elm) {
var dval = $(this).val();
$(elm).data("old", dval).data("temp", dval);
})
}
setData();
//register onchange each input
(function() {
$('#myform :input').change(function() {
var self = $(this);
self.data("temp", self.val());
})
})();
$.fn.extend({
trackChanges: function() {
var self = this,
inps = $(":input", self).not(":input[type=button]").toArray();
inps.some(function(elm) {
var d = $(elm);
if (d.data("old") !== d.data("temp")) {
$(self).data("changed", true);
//console.log($(self))
return true;
}
return false;
})
},
isChanged: function() {
return this.data("changed");
}
});
$("#check").click(check);
&#13;
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<form id="myform">
<input type="text" id="id1" />
<select id="id2">
<option>1</option>
<option>2</option>
</select>
<textarea>asdasd</textarea>
<input type="button" id="check" value="button" />
</form>
&#13;
答案 1 :(得分:-1)
尝试使用此功能,只需添加一行即可。
$.fn.extend({
trackChanges: function() {
/*this will give false during the call ischanged() if no changes is done on
the form */
$(this.form).data("changed", false);
$(":input",this).change(function() {
$(this.form).data("changed", true);});
},
isChanged: function() {
return $(this).data("changed");
}
});