Sunday, August 14, 2016

Dependent Select Box (Part 2)

After spending two weeks learning Javascript, JQuery, and AJAX I at last achieved gained the ability to code a dynamically populated and dependent select box! Let's walk through the process.

I found out, after trying to write the JQuery and such, that I need to learn how to write, get, and parse JSON data. JSON is a complicated, and yet easy at the same time, system to comprehend. What I did was, any time a new item or model in the app was created, Python code would run to write that data to a JSON file. That file could be accessed by the JQuery method $.getJSON.

As I've discussed forms and how to populate the select boxes with Flask in other posts, I will explain the JQuery. It's important to note that Flask will set the select tag with an id (currently I'm not exactly sure where it assigns it from). I only found that by looking at the source code for my site when it was running. It was then easy to assign a variable to that html tag with JQuery. Then the #item_type box could be populated with JQuery that pulled data from the JSON file.

This would be done by looping through the file and appending each option to a string:
'<option value="' + item_type.id + '">' + item_type.name + '</option>'

That string, that ended up being multiple options after the loop, would be added to the html with:
$item_select.html(string of option tags)

Then in a different function would be run when the #item_type box was changed: $item_select.change(function() {}); Inside the change function would run basically the same code to populate the #item_type box option tags. The only differences being it would be for the #item_model box and there would be a conditional block that would add the option only if the model.of_type was the same as the $item_select.val(). Then the string of options would be added to the #item_model box.

Dependent select box achieved!


The only trouble is it would not update in real time. For instance if I would add a new type or model, then go to the page with the select boxes, the new data would not be populated into the box. Through trial and error I found the browser was caching the information and I had to delete the cookies that were being set by (I think) Flask, but the browser could have just been doing that too. After a small Google search I found this little bit of code would set the browser to not cache the cookies:

$.ajaxSetup({
    cache:false
});

Thus ends my journey of the dynamically populated and dependent select box! It seemed like a much higher hill to climb in the beginning but as I'm writing this I wonder how I couldn't figure it all out before.

25 words or less: Better is the end of a matter than its beginning - Solomon

No comments:

Post a Comment