开发者

jQuery - Compare new value with old value on form submit, across all fields (inputs, selects)?

I was reading the answer to this q开发者_JAVA百科uestion, but it solve the problem with just a single field, how would I watch all the fields (input, select, radio, etc...) on a form?

This is what I currently have (I'm using delegate, this form injects to the page dynamically):

$('#preferencesBody').delegate('input[type="radio"], select', 'change', function() {
    var key = $(this).attr('data-key');
    var value = $(this).val();

    // How to get the old value, and compare with the current value, if they are different, call saveUserPreferences?

    Preferences.saveUserPreferences(key, value);
});

Thanks.


$('#formID :input')

will select all input fields (including textarea's and buttons) on a form with id=formID

so your function would look like this..

$('#preferencesBody').delegate(':input', 'change', function() {
  var key = $(this).attr('data-key');
  var value = $(this).val();

  Preferences.saveUserPreferences(key, value);
});


I've rolled my own implementation, using an additional attribute when binding my data, and checking the value against the value of the additional attribute, i.e:

$('#preferencesBody').delegate('input[type="text"]:not(.password)', 'blur', function() {
    var value = $(this).val();
    var currentValue = $(this).attr('data-currentvalue');

    if (value !== currentValue) {
        $(this).attr('data-currentvalue', value);
        Preferences.saveUserPreferences(value);
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜