Search code examples
htmlaccessibilitywai-ariauiaccessibilitywcag2.0

Best accessible way to show a default for a form field


What's the best/recommended way to indicate a form field will have a particular default value if you don't fill it out? I'm especially thinking about fields that are dynamic based on other fields, and wanting it to be correctly accessible.

Think a URL slug. When creating an account, if you fill the field out then that's fine. If you don't, a value will be generated based on your username. But it won't be the same as your username, just generated from it.

Actually setting the form field seems bad because it makes it less obvious you can change it yourself.

I'm not sure if placeholder text works here, but I assume not. I could do an aria-labelledby pointing to something that says "Default value: xyz" but I'm not sure if that will work, or how well it will be understood by screen readers - especially if it's changing automatically.

Cheers


Solution

  • The best way to do this is to populate the input and expose the fact that it was automatically filled in via the label as an extra bit of information.

    Labels on inputs are read once you focus the related input.

    For this reason we can generate labels "on the fly" to contain whatever we want.

    As such the best option here would be to generate the label on blur of the first input that the second input depends on.

    Within the label we add the instructions that explain why this input is already filled in.

    We then auto populate the second input based on the input of the first.

    In the below example I have appended "URL" to the first input value in order to simulate some sort of transformation from username to URL.

    I also remove the explanation in parenthesis if the user has changed the second input value.

    $('#iUsername, #iUserURL').on('blur', function(){
      var ElUserName = $('#iUsername');
      var ElUserURL = $('#iUserURL');
      
      if(ElUserURL.val() == ""){
      
        ElUserURL.val(ElUserName.val() + "URL");
          $('label[for="iUserURL"]').text("user url (you can change this if you want, we have set it as " + $('#iUsername').val() + "URL)");
          
        }else if(ElUserURL.val() != ElUserName.val() + "URL"){  
            $('label[for="iUserURL"]').text("user url");
            
        }
        
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <label for="iUsername">User Name</label><br/>
    <input id="iUsername" /><br/>
    <hr/>
    <label for="iUserURL">User URL</label><br/>
    <input id="iUserURL" /><br/>
    <hr/>
    <label for="itest">I have added this third input just so you have something to tab too, it does not add anything to the fiddle</label><br/>
    <input id="itest" />