Skip to content

Instantly share code, notes, and snippets.

@fprochazka
Created March 1, 2011 12:06
Show Gist options
  • Save fprochazka/849040 to your computer and use it in GitHub Desktop.
Save fprochazka/849040 to your computer and use it in GitHub Desktop.
jQuery event for better testing, whether value has changed
$.fn.valueChange = function (onChange) {
var form = $(this);
var valueChange = {
trigger : function (event) {
$(event.target).trigger('valueChange');
},
store : function (event) {
// saves the actual value to data attribute
var et = $(event.target);
// actual value
et.data('vch-val', et.val()).data('vch-children', et.children().length);
},
testAndTrigger : function (event) {
// compares the saved value and actual value, to decide, whether trigger event or not
var et = $(event.target);
if (et.data('vch-children') != et.children().length) {
et.data('vch-val', et.val()).data('vch-children', et.children().length);
return ;
}
if (et.data('vch-val') != et.val()) {
et.data('vch-val', null).trigger('valueChange');
}
},
setupDatepicker : function () {
form.find('.hasDatepicker').change(valueChange.trigger);
}
};
if (form.length > 1 || form[0].nodeName.toLowerCase() != 'form') {
form.each(function () {
var el = $(this);
if (el.hasClass('vch-notstart')) {
return ;
}
el.bind('valueChange', onChange);
if (el[0].nodeName.toLowerCase() == 'select') {
el.focus(valueChange.store).change(valueChange.testAndTrigger);
} else {
if (el.attr('type').toLowerCase() == 'text' || el[0].nodeName.toLowerCase() == 'textarea') {
el.bind('focus click', valueChange.store).blur(valueChange.testAndTrigger);
} else if (el.attr('type').toLowerCase() == 'checkbox' || el.attr('type').toLowerCase() == 'radio') {
el.change(valueChange.trigger);
} else if (el.attr('type').toLowerCase() == 'submit' || el[0].nodeName.toLowerCase() == 'button') {
el.click(valueChange.trigger);
}
}
});
} else {
form.find(':input:not(.vch-notstart)')
.bind('valueChange', onChange);
form.find(':text:not(.vch-notstart), textarea:not(.vch-notstart)')
.bind('focus click', valueChange.store).blur(valueChange.testAndTrigger);
form.find(':checkbox:not(.vch-notstart), :radio:not(.vch-notstart)')
.change(valueChange.trigger);
form.find('select:not(.vch-notstart)')
.focus(valueChange.store).change(valueChange.testAndTrigger);
}
$(document).ajaxComplete(valueChange.setupDatepicker);
};
$('form#target').valueChange(function (e) { alert('value of ' + e.target.id + ' has changed!'); });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment