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

时间:2015-04-10 14:44:36

标签: javascript jquery asp.net-mvc

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

在我的应用中,用户始终使用模态窗口编辑数据。当模态首次打开时,只有一个“关闭”按钮可见。如果用户更改了任何文本,则会立即隐藏此按钮,并且“取消”和“保存”按钮变为可见。我知道,实现这种方法的唯一方法是将事件连接到所有文本控件。文本控件的数量在表单中有所不同,但不超过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>
$(document).on("change", "#txtUnitNo", function () { EnableButtons(); })
// 49 more text controls 

function EnableButtons() {
    $("#btnCancel").show();
    $("#btnSave").show();
    $("#btnClose").hide();
}

3 个答案:

答案 0 :(得分:4)

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

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

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

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


演示

&#13;
&#13;
$('.changable').on('change', function(e) {
  $('#log').append(e.target.id + ' changed to ' + $(e.target).val() + '<br/>');
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type="text" class="changable" id="input1" />
  <input type="text" class="changable" id="input2" />
  <input type="text" class="changable" id="input3" />
  <input type="text" class="changable" id="input4" />
  <input type="text" class="changable" id="input5" />
</form>

<div id="log"></div>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

试试这个:.change()

所有元素更改中的fire事件(输入,选择,textarea,..)

  $('form').change(function () {
                console.log(this);
                alert('change');
            });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form id="name" action="/" method="post">
        <input type="text" value=" " />
        <select>
            <option value="value">text</option>
            <option value="value">text</option>
        </select>
    </form>

答案 2 :(得分:1)

为所有输入添加一个类,例如'txt-input' @Html.TextBoxFor(m => m.UnitNo, new { @id="txtUnitNo", @class="txt-input"})并使用类来检测更改

$(document).on('change', 'input.txt-input', function() {
  EnableButtons();
});
相关问题