Easy way to find if atleast 1 field (EditorFor mostly on form) is filled RRS feed

  • Question

  • User-173333858 posted

    I need to display an alert when user hits 'cancel' when filling up a form in MVC. It should say, "You have data filled in, are you sure?". The form has a lot of fields. Is there an easy way to find if at least 1 field is filled? 


    Thursday, November 19, 2020 12:51 AM

All replies

  • User1686398519 posted

    Hi RDesh, 

    You can use jquery selector to achieve your needs.I wrote an example, you can refer to it.

        ViewBag.Title = "Index";
        Layout = null;
    @model DailyMVCDemo.Models.TestGetDataModel
    @using (Html.BeginForm("Index", "TestGetData", FormMethod.Post,new { id="testform"}))
        @Html.DisplayNameFor(m => m.Name)
        @Html.EditorFor(m => m.Name)
        @Html.DisplayNameFor(m => m.ID)
        @Html.EditorFor(m => m.ID)
        @Html.DisplayNameFor(m => m.Time)
        @Html.EditorFor(m => m.Time)
        <button type="button" id="cancelbtn">cancel</button>
    <script src="~/Scripts/jquery-3.4.1.min.js"></script>
        $("#cancelbtn").click(function () {
            var flag = true;
            $("#testform :input").each(function () {
                if ($(this).val() != "") {
                    flag = false;
            if (!flag) {
                alert("You have data filled in, are you sure?");

    Here is the result. 

    Best Regards,


    Thursday, November 19, 2020 5:51 AM