JQuery - How to detect the value change on submit?
Is开发者_JAVA百科 there any function available in JQuery to detect the value change of a specific field on submit?
There's change()
.
$('#fieldID').change(
function(){
// do stuff
}
);
You could do something like this:
// document ready
$(function () {
$('form')
// we need to save values from all inputs with class 'confirm'
.find(':input.confirm')
.each(function () {
// save old value in each input's data cache
$(this).data('oldValue', $(this).val())
})
.end()
.submit(function (ev) {
var $changed = $(':input.confirm', this).filter(function () {
return $(this).val() != $(this).data('oldValue')
});
// $changed object contains only changed inputs
// so you can do whatever you want with them
// in your case, display confirmation message
var message = ['Following values have changed! Are you sure you want to save them?\n'];
$changed.each(function () {
message.push(this.name + ' = ' + $(this).val());
});
return window.confirm(message.join('\n'));
});
});
Now, in your form put class="confirm"
on all elements you need to track changes and the script will ask you whether you want to submit new values (also showing what changed and in which fields).
This is perfectly possible to do. Firstly you need use the change event on each select or input to see if it has been changed and set a flag (this flag needs to be global:
var flag = 0;
$('select').change(function(){ flag = 1; } );
Then you need to add a submit event onto the form to see if the flags have been set and then do something else. If you return false from the submit event then the form will not be sent.
$('form').submit(function(){
if (flag == 0) return false; // If the select box has not been changed to not submit the form.
})
This just checks to see if they have been used but not if they are actually different values. If you want to compare the new value to the old one, then on the page load you will need to create an array of the old values then compare them to new ones either on select change or on form submit.
精彩评论