Question

I haven't seen any website do this properly...

If I have two select fields, country and state, then I would code it like so:

<select name="country">
    <option>USA</option>
    <option>France</option>
</select>

<select name="state">
    <option></option>
</select>

I would then populate the state field using AJAX depending on the selection of the country.

However, this is the progressively enhanced state. How would it be done without the use of Javascript? and how should it be enhanced (if the previous example isn't the best way)?

Was it helpful?

Solution

My recommendation is to have a submit button next / below the country drop down. When submitted the server will populate the state for the selected country and sends the response back.

Now, in your javascript on page load hide this button and attach on change handler to the country dropdown and make an AJAX call which will return the states.

So, if the javascript is disabled the button would perform the retrieval of the states. If enabled AJAX call would do the same.

OTHER TIPS

One solution could be to join the two selects together. Like

<select name="countryAndState">
    <option>USA - Alabama</option>
    <option>USA - Alaska</option>
    ...
    <option>France - Alsace</option>
    <option>France - Aquitaine</option>
</select>

or better

<select name="countryAndState">
    <optgroup label="USA">
         <option>Alabama</option>
         ...
    </optgroup>
    <optgroup label="France">
         <option>Alsace</option>
         ...
    </optgroup>
</select>

Of course, at least in the second form you will have to ensure that the option values are unique. The optgroup element is the recommended way to group select options hierarchical in a tree order. That means, your enhancing javascript will also be able to extract the tree structure from DOM.

The other solution would be populating the state field server side, i.e. split your form up in two steps where one first selects the country, then the state. This could be done with a cookie or something to save the selected country; and whenever the submitted value for country differs from the saved value you need to output a new (unselected) state select element.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top