如何检测表单中的数据是否已更改?MVC

Ben*_*ior 2 javascript asp.net-mvc jquery

注意:我已经在这个论坛上看到了一些解决方案,但它们不适用于我的具体情况。

在我的应用程序中,用户总是使用模态窗口编辑数据。当模态第​​一次打开时,只有一个“关闭”按钮可见。如果用户更改任何文本,此按钮将立即隐藏,“取消”和“保存”按钮变为可见。据我所知,实现这种方法的唯一方法是将事件连接到所有文本控件。表单中文本控件的数量不同,但不超过50个。我需要“id”并将“change”事件绑定到表单中的每个控件中。我的问题是,是否有更简单的方法?如果表单中的任何内容发生变化,就像一个事件?如果用户更改数据然后将其改回并且无论如何都会触发该事件,那是可以的。

@using (Html.BeginForm("", "", FormMethod.Post, new { @id = "formPostUnitDetails", @style = "padding-right:5px" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    @Html.HiddenFor(model => model.IdNo)

    @Html.LabelFor(m => m.UnitNo)
    @Html.TextBoxFor(m => m.UnitNo, new { @id="txtUnitNo")
    //..... 49 more text controls 

    <div class="panel-footer" style="margin-top:5px;">
        <input id="btnCancel" type="button" class="btn btn-danger" data-dismiss="modal" value="CANCEL" style=" display: none;" />
        <input id="btnSave" type="button"   class="btn btn-success" value="SAVE CHANGES" style=" display: none;" />
        <input id="btnClose" type="button" class="btn btn-info" data-dismiss="modal" value="CLOSE" />
    </div>
Run Code Online (Sandbox Code Playgroud)
$(document).on("change", "#txtUnitNo", function () { EnableButtons(); })
// 49 more text controls 

function EnableButtons() {
    $("#btnCancel").show();
    $("#btnSave").show();
    $("#btnClose").hide();
}
Run Code Online (Sandbox Code Playgroud)

Joe*_*icz 6

您可以将事件连接到所有输入,而不是将事件处理程序连接到您拥有的每个输入。

$('form input[type="text"]').on('change', function() {
    EnableButtons();
});
Run Code Online (Sandbox Code Playgroud)

这是因为选择器form input[type="text"]选择表单中的所有输入元素(文本类型),然后将change事件处理程序绑定到它们。

另一种选择是分配您想要监视的所有输入,例如change-monitored,然后您可以将选择器更改为$('.change-monitored').on(...)


演示

$('form input[type="text"]').on('change', function() {
    EnableButtons();
});
Run Code Online (Sandbox Code Playgroud)
$('.changable').on('change', function(e) {
  $('#log').append(e.target.id + ' changed to ' + $(e.target).val() + '<br/>');
});
Run Code Online (Sandbox Code Playgroud)