Insights

Attaching Scripts to the Submit Button in Sitecore Forms

Attach custom JavaScript that runs when pressing the submit button without needing to create additional files

How to Attach Custom JavaScript to Your Existing Submit Button

This blog will teach you how to attach custom JavaScript to the existing submit button in Sitecore Forms. It only runs if the form is submitted successfully.

Sitecore Changes First

Firstly, we need to create a template that holds the new field for our scripts. Navigate to /sitecore/templates/User Defined/Features/Sitecore Forms/ and create a new template called Custom Scripts. Add a new Multi-Line Text field with the name Form Submit Script.

CMS interface showing settings for a form submit button including script options

Then go to /sitecore/templates/System/Forms/Fields/Button and add the Custom Scripts template to the base template under the Content tab.

CMS screen displaying button properties with options for model type and view path

C# Code Changes

Create a new class that extends ButtonViewModel. We will be overridiing the following functions: InitItemProperties and UpdateItemFields

using Sitecore;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.ExperienceForms.Mvc.Models.Fields;

namespace MyProject.Feature.SitecoreForms.Models
{
    public class CustomScriptButtonViewModel : ButtonViewModel
    {
        public string FormSubmitScript { get; set; }

        protected override void InitItemProperties(Item item)
        {
            Assert.ArgumentNotNull(item, nameof(item));
            base.InitItemProperties(item);
            FormSubmitScript = StringUtil.GetString((object)item.Fields["Form Submit Script"]);
        }

        protected override void UpdateItemFields(Item item)
        {
            Assert.ArgumentNotNull(item, nameof(item));
            base.UpdateItemFields(item);
            item.Fields["Form Submit Script"]?.SetValue(FormSubmitScript, false);
        }
    }
}

Notice the Form Submit Script field that we added in Sitecore.

Finally, navigate to the existing Button view at Views/FormBuilder/FieldTemplates/Button.cshtml

We will be adding the following code to the end of Button.cshtml. Read the comments in the code for more details.


<script type="text/javascript">
    function () {
            // get the input object
        var $input = $("input[name='@Html.Name(Model.ItemId)']");
        // get the form object by finding the closest form
        var $form = $input.closest('form');

                // exit if there is no form
        if ($form.length == 0) {
            return;
        }        

                // If the button has a script attached to it, run
        @if (!string.IsNullOrWhiteSpace(Model.FormSubmitScript)) {

            <text>
            $form.on("submit", function () {
                // on form submit, wait 1000 milliseconds for it to submit then check
                setTimeout(function () {
                        // if the form is filled out incorrectly and fails to submit, 
                        // Sitecore will add a novalidate attribute to the form with the value novalidate
                    var validateError = $form.attr("novalidate");
                    // if the form doesn't have the error, run the script
                    if (validateError != "novalidate") {
                        @Html.Raw(Model.FormSubmitScript)
                    }
                }, 1000);


            });
            </text>
        }

    });
</script>

Finishing Up in Sitecore

Now that we have our new class created, go to /sitecore/system/Settings/Forms/Field Types/Structure/Submit Button and change to Model Type field to: MyProject.Feature.SitecoreForms.Models.CustomScriptButtonViewModel,MyProject.Feature.SitecoreForm.

Content management system interface for form templates and custom script settings

And finally, we can go to an existing button on one of our forms, and add a script. Here is an example

CMS forms section highlighting custom scripts with options for form submit script

Now when we submit the form successfully, you will see a printed message in the console.

Attaching Custom Scripts to Submit Buttons

Thank you for reading my blog on how to attach custom JavaScript to the Sitecore submit button. I find it easier than creating a new JS file and doing event binding.



Meet Gorman Law

Full Stack Developer

🏋️🎸🏈

Gorman is a Full Stack Developer and a University of Calgary alumni who has a background in Canada's financial industry. Outside of work, he likes to go rock climbing, try out new ice cream places, and watch sports.

Connect with Gorman