2

I have a form with many fields in an MVC application. I am using javascript to detect any changes in any of the fields via the following javascript:

var _changesMade = false;

    // Catch any other changes made and flag model as changed.
$('form').bind('change', function () {
    _changesMade = true;
    $("#ContractorName").val(null);
    $("#ContractDateApproved").val(null);
    $("#Verified").attr('checked', false);
});

// Warn user if there are unsaved changes.
$(window).bind('beforeunload', function () {
    if (_changesMade)
        return 'There are unsaved changes which will be lost if you continue.';
});

However, there is one field (a checkbox called Verified) that I want to handle differently and NOT do the default changes made in the form change event.

Is there a way to tell the $('form').bind('change') to ignore any changes to the verified checkbox? I want to handle it differently in the checkbox's "click" event.

Or, is there a way that I can determine in the "change" event logic what element in the form caused the change event to fire off? That way, I can check to see if it was the Verified checkbox that changed and ignore the event.

Thanks.

4

3 回答 3

2

你应该使用 event.target

$('form').bind('change', function (e) {

    if(e.target == $('#Verified').get()[0]){
        return ;
    }
    _changesMade = true;
    $("#ContractorName").val(null);
    $("#ContractDateApproved").val(null);
    $("#Verified").attr('checked', false);
});

这是一个jfiddle。

http://jsfiddle.net/NtYzn/

于 2013-09-11T20:07:14.557 回答
1

如果我理解正确,您想对复选框做一些不同的事情。您可以使用该stopImmediatePropagation方法阻止其他处理程序捕获该事件。

$('#Verified').bind('change', function(event) {
    event.stopImmediatePropagation();
    //do whatever you need to here.
});

$('form').bind('change', function () {
    //do whatever you need to here.
});

提琴手

于 2013-09-11T20:05:06.353 回答
0

尝试:

$('input:checkbox').unbind('change'); // Do this after the form bind

或者

// Inside the change method
if (!$(this).is('input:checkbox')) {
  _changesMade = true;
}
于 2013-09-11T20:02:42.157 回答