Question

I have a form that contains a select field that is only shown when the value of the previous select field is set to a specific value. Here is a simplified version where a hidden "states" select field appears if "USA" is selected as the country:

HTML:

<style>
  label {
    display:inline-block;    
    min-width:100px;        
    padding:3px;
  }
  .hidden{
    display:none;
  }
</style>

<div>
  <label for="country">Country</label>
  <select id="country">
    <option>Czech Republic</option>
    <option>USA</option>
  </select>
</div>
<div id="stateContainer"  class="hidden">
  <label for="state">State</label>
  <select id="state">
    <option>Alabama</option>
    <option>Arizona</option>
    <option>Arkansas</option>
  </select>
</div>
<div>
  <label for="name">Name</label>
  <input type="text" id="name" />
</div>

JS:

$(function(){
  $("#country").on("change",function(){
    if ( $(this).val() === "USA") {
      $("#stateContainer").removeClass("hidden");
    } else {
      $("#stateContainer").addClass("hidden");
    }
  })
})

...and here it is in JSFiddle:

http://jsfiddle.net/xoundboy/a2HdZ/5/

it works fine when using a mouse but if the user is restricted to keyboard input only then UX is broken. You can see this if focus is in the country field and you use the up/down arrows to select "USA" as the country and then the tab key to move to the next field. Instead of moving to the newly shown "state" field, it skips over to the "name" field.

I could probably fix it by capturing the tab key press in JS, forcing the focus onto the newly shown field and preventing default behaviour but that seems like an ugly hack. What is the best practice for handling what must be quite a common scenario?

Was it helpful?

Solution

The change event is not triggered when up/down key is pressed. So the change event can be triggered on a key press.

js fiddle example for the code changes. Hope it helps.

EDIT 1 I checked with different browsers and found out that this problem is in firefox and hence the solution is for firefox. For chrome the fiddle in question works perfectly fine for me.

EDIT 2 My previous fiddle had change triggered on keypress. It seems firefox changed somethings and it no more works. I have updated the event to keyup.

OTHER TIPS

just use the tabindex element property, tab order goes from lowest to highest value

Fiddle

<div>
  <label for="country">Country</label>
  <select id="country" tabindex=1>
    <option>Czech Republic</option>
    <option>USA</option>
  </select>
</div>
<div id="stateContainer"  class="hidden">
  <label for="state">State</label>
  <select id="state" tabindex=2>
    <option>Alabama</option>
    <option>Arizona</option>
    <option>Arkansas</option>
  </select>
</div>
<div>
  <label for="name">Name</label>
  <input type="text" id="name" tabindex=3 />
</div>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top