conditionally disabling the submit button on the hosted login pages
-
On the registration page, I want to disable the submit button if the required fields aren't filled out.
How can I do this?
-
This is a job for javascript and customizing the theme.
For the registration page, modify the
oauth register
template. Edit that theme, then find where we create the form, marked by this comment in the default theme.[#-- Begin Self Service Custom Registration Form Steps --]
From there, find the 'register' button.
[@helpers.button icon="key" text=theme.message('register')/]
Change it to disabled by default:
[@helpers.button icon="key" text=theme.message('register') disabled=true/]
Then you need to build the JS which adds/removes the
disabled
attribute and thedisabled
CSS class based on the fields that are required. Luckily, we have those fields as a template variable,fields
and can iterate that in freemarker.Here is some javascript. It needs to be below the register button as it references elements in the form above. It builds a list of required fields and then adds a listener to each required field checking to see if any of the fields are empty. I'm no JS expert, so feel free to modify as needed.
<script type="text/javascript"> let reqFields = []; // build a list of required fields in JS from the freemarker template variable. [#list fields as field] [#assign fieldId = field.key?replace(".", "_") /] [#if field.required] reqFields.push("${fieldId!''}"); [/#if] [/#list] [#list fields as field] [#assign fieldId = field.key?replace(".", "_") /] [#if field.required] ( () => { // we're doing this in an anonymous function so we don't get variable collisions. we could have 0 to N required fields. let inputElt = document.getElementById('${fieldId!''}'); let btn = document.querySelector("form.full button"); inputElt.addEventListener("input", function() { let disabled = false; const keys = reqFields.keys(); for (let x of keys) { let reqFieldEmpty = document.getElementById(reqFields[x]).value === ''; if (reqFieldEmpty == true) { // console.log("found: "+reqFields[x]+" to be empty"); disabled = true; break; // any one empty field will mean button is disabled. } } // we've determined if the button should be disabled, now apply it btn.disabled = disabled; if (!disabled) { btn.classList.remove("disabled"); } else { btn.classList.add("disabled"); } }); } )(); [/#if] [/#list] </script>
Feel free to modify this logic as needed to fit your theme.