Tying together different select elements in a form is done with very little effort thanks to the ajax and states system built into Drupal 9. This means that any Drupal form can have a select element that shows and updates options into another select element within the same form. Using this system you can create a hierarchical system where one select will show and populate another select element with items dependent on the first. This is great for giving the user the ability to drill down into options that are dependent on each other. As the user selects the first select element the second select element will populate with data and be shown on the screen.
I tried to do something the other day that I thought would be quite simple, but turned out to be really hard to get my head around. I had a Drupal 9 site with Paragraphs installed and I wanted a user to click a button on the node edit form and inject a particular Paragraph into a Paragraph field.
I found 2 solutions to this problem that solve it in slight different ways.
Piggy Back On Existing Events
After my initial struggles over trying to get this to work I decided to use a piggy back method. This essentially listens for the user interaction and then triggers the Paragraph add event that inserts the Paragraph into the field. The user interaction I was listening for was a user selecting different elements in a select list.
This problem came out of a recent project I was working on. I had to perform a bunch of API lookups on behalf of a user that could take a minute or so to complete. The results of the API lookups were cached and so once it was done the site would be very quick, unfortunately the initial API lookup slowed down the page load quite considerably so this created a problem.
Rather than just doing the API loading in the page load process and making the user sit through it I created a batch process to load the API results in a more manageable manner. This created another problem as although the batch runner in Drupal is really good, it is perhaps a little too much just to show to users and expect them to understand what is going on. This led me to think if I could run a batch process via an AJAX callback from the page they were trying to load.
How To Use Them
Using the Google Ajax libraries on your own site is quite easy, and you can do it in a number of different ways.
Normally, you would download the latest and greatest version of your chosen library and upload it to your site. Here is an example using the MooTools.