简体   繁体   中英

Javascript-less dependent drop-downs

In my application users are asked to input:

  • State -> City
  • Category -> Sub-Category

City depends on State and Sub-Category depends on Category . I would like it works without javascript first and then to add an unobtrusive javascript to improve user experience.

How would you implement it? Ask all independent fields at once? Create multi-step form with many steps? Any other possibilities?

To make it work without Javascript, you would need a procedure like:

  • Select state.
  • Press a button that posts the form to the server.
  • Return a page with the selected state and the cities to choose from.
  • Press a button that posts the form to the server again.

Without scripting the browser can't do anything depending on what you choose in the first step, so you have to do that on the server side.

Without JS this would sorta suck. You would:

  1. select a state
  2. click "next"
  3. server receives what state you chose, and renders a new page with a drop down full of relevant cites
  4. select a city
  5. click next
  6. Something happens

But with JS the user experience becomes:

  1. select a state
  2. city drop down appears
  3. select a city
  4. something happens

Without JS everytime you want to change the page you must make the server render you a fresh pag ein that new state. And for tasks like this, that just kinda sucks.

Try using an <optgroup>

<select name="cities">
  <optgroup label="State_one">
    <option value="City_one">City one</option>
    <option value="City_two">City two</option>
  </optgroup>
  <optgroup label="State_two">
    <option value="City_three">City three</option>
    <option value="City_four">City four</option>
  </optgroup>
</select>

You can do some CSS hackery with the :active pseudo class if you want two selects side by side.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM