Search code examples
javascriptformsvalidationrazoroauth-2.0

How to enable a submit button if form fields are auto-filled by the browser using saved credentials on page load?


I'm working on a login form where the submit button should be enabled only if both the username and password fields are filled. My current JavaScript code works fine when the user manually enters the credentials or if they are auto filled by the browser at a later stage, but it doesn't work as expected when the fields are pre-filled by the browser's saved credentials upon page load. Here's my code in the script tag inside a razor file:

function validateForm() {
    var username = document.getElementById('Username').value;
    var password = document.getElementById('Password').value;
    var submitButton = document.getElementById('ActionSubmit');

    if (username && password) {
        submitButton.disabled = false;
        submitButton.style.backgroundColor = '#abcdef';
        submitButton.style.color = '#000000';
        submitButton.style.cursor = 'pointer';
    }
    else {
        submitButton.disabled = true;
        submitButton.style.backgroundColor = '#fedcba';
        submitButton.style.color = '#ffffff';
        submitButton.style.cursor = 'not-allowed';
    }
}

document.getElementById('Username').addEventListener('input', validateForm);
document.getElementById('Password').addEventListener('input', validateForm);

window.addEventListener('load', function () {
    validateForm();
});

The submit button remains disabled if the browser automatically fills in the username and password fields using saved credentials when the page loads. The button only gets enabled if the user manually interacts with the page (even a simple click anywhere on the screen fixes it) after the page has loaded.

I suspect this issue occurs because my validateForm function is executed before the browser has a chance to populate the fields with the saved credentials, and since no further interaction happens, the function doesn't get called again.

Any advice on handling this would be greatly appreciated!


Solution

  • I discovered that when the browser autofills credentials, they aren't actually bound to the form fields until the user interacts with the form (even a simple click does the trick). This is likely a security measure to ensure user consent. I tried logging the form field values to the console, but despite the fields appearing autofilled, the values weren't bound until user interaction. This explains why the login button remains disabled until the fields are properly bound, which can be unintuitive for users. To address this, I implemented a validation check on login button click, ensuring the autofilled values are bound and preventing form submission if any fields are empty.