0

i have the following razor of a form

@using (Ajax.BeginForm(new AjaxOptions { }))
{
    <div id="frm" style="visibility:hidden">
    <table>
    <thead>
        <tr>
            <td></td>
            <td></td>
            <td></td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>@Html.LabelFor(x => x.emp.FirstName, new { @class = "form-control" })</td>
            <td>@Html.TextBoxFor(x => x.emp.FirstName, new { @class = "form-control" })</td>
            <td>@Html.ValidationMessageFor(x => x.emp.FirstName)</td>
        </tr>
         <tr>
            <td>@Html.LabelFor(x => x.emp.LastName, new { @class = "form-control" })</td>
            <td>@Html.TextBoxFor(x => x.emp.LastName, new { @class = "form-control" })</td>
            <td>@Html.ValidationMessageFor(x => x.emp.LastName)</td>
        </tr>
         <tr>
            <td></td>
            <td></td>
            <td>
                <input type="submit" value="Save" class="btn btn-success" id="save"/>
                <input type="submit" value="close" class="btn btn-success" id="close"/>
            </td>
        </tr>
    </tbody>
</table>
        </div>
}

when i click the close button the forms hides and the validation should get cleared. But validation clearing part does not work... How do i clear the validations by clicking close button?

UPDATE: here is my complete code

@model EmployeesTest.Models.EmployeeVM

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

<input type="submit" name="name" value="New Entry" id="new"/>

@using (Ajax.BeginForm(new AjaxOptions { }))
{
    <div id="frm" style="visibility:hidden">
    <table>
    <thead>
        <tr>
            <td></td>
            <td></td>
            <td></td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>@Html.LabelFor(x => x.emp.FirstName, new { @class = "form-control"})</td>
            <td>@Html.TextBoxFor(x => x.emp.FirstName, new { @class = "form-control", id="firstName" })</td>
            <td>@Html.ValidationMessageFor(x => x.emp.FirstName)</td>
        </tr>
         <tr>
            <td>@Html.LabelFor(x => x.emp.LastName, new { @class = "form-control" })</td>
            <td>@Html.TextBoxFor(x => x.emp.LastName, new { @class = "form-control", id="lastName" })</td>
            <td>@Html.ValidationMessageFor(x => x.emp.LastName)</td>
        </tr>
         <tr>
            <td></td>
            <td></td>
            <td>
                <input type="button" value="Save" class="btn btn-success" id="save"/>
                <input type="button" value="close" class="btn btn-success" id="close"/>
            </td>
        </tr>
    </tbody>
</table>
        </div>
}


@section Scripts {
    <script>
        $(document).ready(function () {

            $('#new').load(x, function (y) {
                var form = $('#frm');
                form.data('validator', null);
                $.validator.unobtrusive.parse(form);
            });

            $('#new').click(function (evt) {
                //evt.preventDefault();
                $('#frm').css('visibility', 'visible');

            });

            $('#save').click(function (evt) {
                //evt.preventDefault();

                //$('#frm').css('visibility', 'visible');

            });

            $('#close').click(function (evt) {
                //evt.preventDefault();
                resetValidations();

                $('#frm').css('visibility', 'hidden');

            });

            function resetValidations() {
                //var validator = $('#frm').validate();
                //$('#frm').find('.field-validation-error span').each(function () {
                //    validator.settings.success($(this));
                //});
                //validator.resetForm();

                $('#firstName').addClass('input-validation-valid');
                $('#firstName').removeClass('input-validation-error');

                $('#lastName').addClass('input-validation-valid');
                $('#lastName').removeClass('input-validation-error');
            }

        });



    </script>
}

Here is the Model class EmployeeModel

public class EmployeeModel
{
    public int EmpID { get; set; }

    [Required]
    public string FirstName { get; set; }

    [Required]
    public string LastName { get; set; }
}

VM

public class EmployeeVM
{
    public string DepartmentID { get; set; }
    public List<SelectListItem> DepartmentColl { get; set; }

    public EmployeeModel emp { get; set; }

    public EmployeeVM()
    {
        emp = new EmployeeModel();
    }
}
Phill Greggan
  • 2,234
  • 3
  • 20
  • 33
  • Please check http://stackoverflow.com/questions/2798427/how-do-i-clear-mvc-client-side-validation-errors-when-a-cancel-button-is-clicked?answertab=active#tab-top – Parth Trivedi Jan 12 '16 at 06:58
  • @ParthTrivedi i have tried it it did not work! when the forms loads and click save checks for validations and shows errors but when i click close after that the form does not even close – Phill Greggan Jan 12 '16 at 06:59
  • 2
    One option is to reparse the validator ([refer this answer](http://stackoverflow.com/questions/31768946/required-field-validations-not-working-in-jquery-popup-mvc-4/31769058#31769058)). But your Close button should not be `` which will trigger validation. Instead use ` –  Jan 12 '16 at 07:01
  • Please change `type="button"` instead of `type="submit"` – Parth Trivedi Jan 12 '16 at 07:03
  • You can add a css class of cancel to a submit button to clear or reset the validations. `` – Mox Shah Jan 12 '16 at 07:08
  • @StephenMuecke sorry Stephen i got really messed up with the code now button click of #new button does not even work.. i have updated my original post – Phill Greggan Jan 12 '16 at 07:31

1 Answers1

2

First, I suggest the enclosing div in your form be styled with display:none rather than visibility: hidden (refer this answer for the difference)

<div id="frm" style="display:none">

Your "New Entry" button should be a normal button, not a submit button (its purpose is to show the form, not to submit it)

<button type="button" id="new">New Entry</button>

Then its associated script will be

$('#new').click(function () {
  $('#frm').show();
});

Note your $('#new').load() script should also be deleted (its not clear what you think this is doing)

Next you "Close" button should also be a normal button for the same reasons as above

<button type="button" class="btn btn-success" id="close">Close</button>

and its associated script to reset the form and validation will be

$('#close').click(function () {
  //Reset error messages
  $('.field-validation-error').empty().removeClass('field-validation-error').addClass('field-validation-valid');
  //Reset form controls
  $('#frm').get(0).reset();
  $('.input-validation-error').removeClass('input-validation-error').addClass('valid');
  // Reset lazy validation
  $('#frm').data('validator', null);
  $.validator.unobtrusive.parse($('#frm'))
  // Hide the form
  $('#frm').hide();
});

Side note: Suggest the first line in the <script> tags be var form = $('#frm'); and then you can replace all instances of $('#frm') with form (it caches the element so is more efficient). In fact you really don't need the <div id="frm" style="display:none"> element, because you can just show/hide the <form> element itself

Note also you can use a reset button for the "Close" button - <button type="reset" class="btn btn-success" id="close">Close</button> and delete the $('#frm').get(0).reset(); line of code.

Community
  • 1
  • 1
  • thanks for taking time to answer the question but the problem still exists here is the video to show that https://youtu.be/9Gvnxihy7gg – Phill Greggan Jan 12 '16 at 09:55
  • You also changed the "Save" button to a normal button - that one needs to be a submit button (as per your original code) –  Jan 12 '16 at 10:15
  • There is also a potential issue because the form is hidden depending on how the validator is configured. Can you temporarily remove the `style="display:none"` from the `div` so its displayed when you first render the view for testing purposes –  Jan 12 '16 at 10:18
  • i did that too now the form shows at page load but still buttons dont work – Phill Greggan Jan 12 '16 at 10:23
  • Are you getting any errors in the browser console? I'll check the video again for any typos you have have –  Jan 12 '16 at 10:24
  • here are the errors on browser Uncaught: TypeError: $(...).get(...).reset is not a functionresetValidations @ (index):104(anonymous function) @ (index):84jQuery.event.dispatch @ jquery-2.1.4.js:4435elemData.handle @ jquery-2.1.4.js:4121 – Phill Greggan Jan 12 '16 at 10:26
  • Not sure why, but just temporarily comment out the `$('#frm').get(0).reset();` line. (Its purpose is to reset the value of the form elements (so if you enter "xyz" in a textbox, it will reset back to its initial value - i.e. empty) –  Jan 12 '16 at 10:29
  • when i do that there were no console errors and form hides but when i click New entry again it shows the form with the validation message – Phill Greggan Jan 12 '16 at 10:32
  • Assume this seems a bit unorthodox if so, in a situation like this where the form and its displaying button and closing buttons are in the same page how to clear validations, how to do it properly? – Phill Greggan Jan 12 '16 at 10:37
  • I'll create a DotNetFiddle for you, but bit busy at the moment - give me an hour –  Jan 12 '16 at 10:42
  • 1
    Oops,Just realized I left off `.empty()` to remove the inner error `span` element that contains the error text (see edit). Refer [this DotNetFiddle](https://dotnetfiddle.net/RG1bUC) for a working example. Note the `$('#frm').get(0).reset();` works fine but as an alternative, delete that line and make the button `` which does the same thing. Also there is no real need to the ` –  Jan 12 '16 at 11:21