Tuan nguyen
Tuan nguyen

Reputation: 570

Form change best practice

In my template I have a country select box, and province element which changed dynamically based on country. For example, If I select United States, Province will be a selectbox which include US States. If i select other country, Province will be only a text field. I know that I have to do that by Javascript but I want to know the best practice in this case. Any suggestion?

Upvotes: 0

Views: 125

Answers (1)

Nicolai Fröhlich
Nicolai Fröhlich

Reputation: 52483

This question arises almost daily on stackoverflow ... How to handle sub-select's like country->state ...?

Best practice for multiple related select field types is only loading the first selectbox from database with a dedicated submit button for adding the subselects - could be "show states" or similar in your case.

Don't fetch all the possible sub-selects when rendering the form the first time. This could easily lead to heavy database queries if you show something like country -> state -> city for example ... but country -> state for all countries is already too much.

If the form was submitted using the "show states" button add the related sub-select to the form together with either a "show cities" button or if no other sub-selects will be loaded .. with the final "save" button.

This way a user without JavaScript can use the double-select without the at first unneeded subselect queries involved. Just hiding the second select with JS is not best practice.

Progressive enhancement through JavaScript would then be AJAX-Loading i.e. a JSON list of the states for a country, removing the "show states" button , rendering the data using JS templating engines like handlebars or mustache and adding the "save" button.

This way you don't have to send too much repetetive data to the client browser ( option,option,option ... ).

Last step would be caching client and server-side to speed up the loading times - maybe even involve some kind of background preloading i.e. the top 5 choices for the client's preferred language.

Upvotes: 1

Related Questions