0

I have a form in ASP.NET MVC5 that uses FormMethod.Post I have a Create button that submits the form, but how would I get it to work so that if you click Create then it disables the button. I have tried:

onclick="this.disabled = true"

But then the form is not submitted, hower when it is removed it allows you to add multiple records when clicking Create

This is my code for the form:

    @section scripts {
    @Scripts.Render("~/bundles/jqueryajaxval")
    @Scripts.Render("~/bundles/jqueryval")

    <script language="javascript" type="text/javascript">
        // cancel
        $(document).on("click",
            "#CancelForm",
            function(e) {
                var uri = '@Html.Raw(Url.Action("Index", "Membership"))';
                window.location = uri;
                e.preventDefault();
            });

        // submit
        $(document).on("click", "#submitMembership", function(e) {
                // Perform Ajax request to check if CAE/IPI Number is unique.
                var caeipinumber = $('#addMembershipCAEIPINumber').val();
                if (caeipinumber) {
                    $.ajax({
                        url: '@Url.Action("IsCAEIPINumberUnique", "Membership")',
                        data: ({ 'caeipinumber': caeipinumber, 'personaIdToIgnore': null }),
                        type: 'POST',
                        async: false,
                        cache: false,
                        success: function(result) {
                            if (result.toLowerCase() == "false") {
                                // Number is not unique and already exists, so display validation error to the user.
                                e.preventDefault();
                                $('#addMembershipForm').validate().showErrors({ 'CAEIPINumber': 'CAE / IPI Number already exists!' });
                                return false;
                            }
                            return true;
                        },
                        error: function(xhr, status, error) {
                        }
                    });
                }
            });
    </script>
}

@section additionalStyles {

}

@section modal {

}

<article class="row">
    <h1 class="pageTitle artistHeader fw200 mb20 mt10">@ViewBag.Title</h1>

    <div class="col-md-1"></div>
    <div id="createMembership" class="col-md-10 formContainer">
        <div class="panel">
            <div class="panel-heading">
                <span class="panel-title">
                    <i class="glyphicon glyphicon-pencil"></i>&nbsp;Details of New Membership
                </span>
            </div>

            @using (Html.BeginForm("AddMembership", "Membership", FormMethod.Post, new { id = "addMembershipForm", role = "form", @class = "theme-primary form-horizontal" }))
            {
                <fieldset>
                    <legend style="display: none">Add Membership Form</legend>
                    @Html.AntiForgeryToken()
                    @Html.ValidationSummary(true)
                    <div class="panel-body p25 fill bt0 pbn">
                        <div class="form-group">
                            @Html.LabelFor(x => x.MembershipName, new { @class = "control-label col-md-3" })
                            <div class="col-md-8">
                                @Html.TextBoxFor(x => x.MembershipName, new { id = "addMembershipName", @class = "form-control", placeholder = "Enter Membership Name..." })
                                @Html.ValidationMessageFor(x => x.MembershipName, string.Empty, new { @class = "text-danger" })
                            </div>
                        </div>
                        <div class="form-group">
                            @Html.LabelFor(x => x.CAEIPINumber, new { @class = "control-label col-md-3" })
                            <div class="col-md-8">
                                @Html.TextBoxFor(x => x.CAEIPINumber, new { id = "addMembershipCAEIPINumber", @class = "form-control", placeholder = "Enter CAE / IPI Number..." })
                                @Html.ValidationMessageFor(x => x.CAEIPINumber, string.Empty, new { @class = "text-danger" })
                            </div>
                        </div> 
                    </div>
                    <div class="panel-footer">
                        <div class="text-center">
                            <input type="button" class="btn btn-primary" id="CancelForm" value="Cancel" />
                            <input id="submitMembership" type="submit" class="btn btn-primary" value="Create" />
                        </div>
                    </div>
                </fieldset>
            }
        </div>
    </div>
    <div class="col-md-1"></div>
</article>
2
  • Why not disable in the click-handler? Commented Apr 20, 2018 at 14:47
  • How do you mean? Commented Apr 20, 2018 at 14:59

3 Answers 3

1

You should listen the form submit event, the submit input used trigger the form submit event and when the event is triggered you can disable the Button you clicked.

$("#form1").submit(function (){
   $("#submitbtn").prop ("disabled",true);
   $.ajax({requestprops,success:function(){
             $("#submitbtn").prop ("disabled",false);
    }});
});
Sign up to request clarification or add additional context in comments.

Comments

0

This should work:

<script>
function setDisable(id) {
    document.getElementById(id).disabled=true;
};
</script>

 <input id="submitMembership" type="submit" onclick="setDisable(this.id)" class="btn btn-primary" value="Create" />

Comments

0

First, I would remove the binding on the click of the submit button and instead bind on the submit event.

Replace your submit button function with the following:

$("#addMembershipForm").submit(function (e) {
            var submitButton = $(this).find(':input[type=submit]').prop('disabled', true); // Find and disable the submit button
            // Perform Ajax request to check if CAE/IPI Number is unique.
            var caeipinumber = $('#addMembershipCAEIPINumber').val();
            if (caeipinumber) {
                $.ajax({
                    url: '@Url.Action("IsCAEIPINumberUnique", "Membership")',
                    data: ({ 'caeipinumber': caeipinumber, 'personaIdToIgnore': null }),
                    type: 'POST',
                    async: false,
                    cache: false,
                    success: function(result) {
                        if (result.toLowerCase() == "false") {
                            // Number is not unique and already exists, so display validation error to the user.
                            submitButton.prop('disabled', false); // Enable submit button
                            e.preventDefault(); // Do not submit form
                            $('#addMembershipForm').validate().showErrors({ 'CAEIPINumber': 'CAE / IPI Number already exists!' });
                        }
                    },
                    error: function(xhr, status, error) {
                    }
                });
            }
      });

var submitButton = $(this).find(':input[type=submit]').prop('disabled', true);is used to find and then disable the button.

It will then do your unique check the same as you had in your original question. However, we will enable the submit button if it returns false so the user can re-submit.

2 Comments

There is an issue when you click on create the button is disabled and it does not submit the form.
So you are checking if CAE/IPI Number is unique and then if true - you are submitting the form? I will revise my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.