Skip to content

Instantly share code, notes, and snippets.

@brianaohern
Created July 17, 2018 14:26
Show Gist options
  • Save brianaohern/53268b712caa697ecfea37b1ec8dfecc to your computer and use it in GitHub Desktop.
Save brianaohern/53268b712caa697ecfea37b1ec8dfecc to your computer and use it in GitHub Desktop.
Custom Required Script
<script type="text/javascript">
var form = document.querySelector('html div#om-YOUR-OPTIN-SLUG .NAMESPACE-FieldsElement--content');
var errorAlert = document.querySelector("html div#om-YOUR-OPTIN-SLUG .NAMESPACE-FieldsElement--content #errorAlert");
var formSubmitButton = document.querySelector("html div#om-YOUR-OPTIN-SLUG .NAMESPACE-FieldsElement--content input.om-trigger-conversion"); /* This variable is a flag to know if a user has attempted to submit at least once. */
var attemptToSubmitAtLeastOnceFlag = false; /* This code hides the error field. */
function fieldsCheck() {
var lookForInvalidInputs = document.querySelectorAll('html div#om-YOUR-OPTIN-SLUG .NAMESPACE-FieldsElement--content :invalid'); /* Scan Form for All Inputs that currently have a :placeholder-shown pseudo-class */
var lookForInputsShowingPlaceholders = document.querySelectorAll('html div#om-YOUR-OPTIN-SLUG .NAMESPACE-FieldsElement--content :placeholder-shown'); /* If there are no "invalid" states OR Placeholder States, then the table will be 0 */
if (lookForInvalidInputs.length > 0 || lookForInputsShowingPlaceholders.length > 0) { /* If the inputs are invalid, show the Error Message and Disable the Submit button */
formSubmitButton.disabled = true;
errorAlert.style.display = "block";
} else { /* If the inputs are valid, remove the Error Message and Enable the Submit button */
errorAlert.style.display = "none";
formSubmitButton.disabled = false;
}
}
/* --------------------Event Listeners Below --------------------- */
/* As keys are pressed, check to see if the fields have been validated to allow input. If fields are valid, run 'fieldsCheck' function. The key down function will only display the Error Message after the user attempts to press the Submit Button once. */
form.addEventListener("keydown", function() {
if (attemptToSubmitAtLeastOnceFlag == true) {
fieldsCheck();
}
});
formSubmitButton.addEventListener("click", function() {
attemptToSubmitAtLeastOnceFlag = true;
fieldsCheck();
formSubmitButton.click();
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment