The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Populating a dropdown inline, or with ajax

  • This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
  • #201130

    I have a city dropdown that starts blank and gets populated based on which province is selected in a dropdown via an AJAX call. Just using straight up jquery.

    The server can sometimes be a bit slow, so we thought of populating the dropdown dynamically so all the data is already there on pageload (it’s not a huge list)

    But then I’m not sure if there is a good way to store that data on the page that doesn’t seem a bit … weird or convoluted

    1. write a script tag directly in the page – pollutes global scope, I think generally frowned on.
    2. a data attribute on each province <option> list stores an array or JSON string of the possible cities for that province, on change we grab that string, iterate through it and replace the options in the current dropdown. I’ve read that JSON in a data attribute is not always the best idea (quotes get weird..)
    3. have a hidden dropdown that has all the options, tagged with their province. on change of the first dropdown, we pull out the options with the correct province and replace the options in the visible dropdown. This seems like the best method so far.

    How would you approach this?

    Kenechi Egbuna

    I like number 1. If you have a global object you’re already using you can make this data a part of it, i.e. or something. Otherwise you could also take those results and stuff them into the localstorage keyed by their provinces.

Viewing 2 posts - 1 through 2 (of 2 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.