Using jQuery

jQuery is a library that we can use to update the HTML of the page from JavaScript. Here are some short tutorials on how to do things in jQuery:

Starting with jQuery

Before we do anything else with jQuery, we'll need to set it up. To do it, we'll add this code to the page, within the <head> tag:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>

Alright, now we have jQuery loaded, and we can use it to make our page interactive. I've included some examples of what you can do below:

Doing something when the user clicks a button

Let's create a button that does something when the user clicks it. (Note: while it's possible to do this using the onclick attribute, it's generally prefereable to keep your JS seperate from your HTML code itself, so we prefer doing it this way.)

First, let's create a button in our HTML.

<button id="our_button">Click me!</button>

Note the id—this must be different for every button, and we'll use it later to find the button. Now, let's add some JavaScript:

$("#our_button").click(function() {
  alert("You clicked the button!")
})

OK, let's break this down. First, we have this bit:

$("#our_button")

jQuery adds a function called $. (Yes, the function name is just a dollar sign. Don't question it.) The function "looks up" one or more elements on our page. We give it a string (called a "selector") that tells it what element to look up. In this case, we start the string with a # to indicate that we're looking for the element with a certain id.

Now that we've found the button, we can do things with it, such as telling jQuery to do something when it gets clicked. We do that with the click function, like so:

$("#our_button").click(function() {
  // code goes here
})

Finally, we fill in the code we want to run when we click the button, such as the alert("You clicked the button!") in the example.

Alternatively, if you already have a function you want to use when you click the button, you can use that instead:

// Let's say we have a function called do_the_thing that we already wrote,
// and we want that function to get called when someone clicks our button.
$("#our_button").click(do_the_thing) // Important: no () after do_the_thing

Adding elements to the page

Let's say we just got some results back from the database, and we want to show them to the user. In the database example, I did this with alert(), like so:

<script>
  async function doADatabaseQuery() {
    var results = await query(sql`SELECT * FROM schools`)
    results.forEach(function(result) {
      alert("The name of this result is " + result.name)
    })
  }

  doADatabaseQuery()
</script>

However, we could make this much nicer if we actually showed our results on the page instead of just displaying them for a second. We can do this with jQuery. To do so, let's start by creating the table we'll show our results in:

<table>
  <thead>
    <!-- The header for our table -->
    <tr>
      <th>Name</th>
      <th>Address</th>
    </tr>
  </thead>
  <tbody id="table_body">
    <!-- The actual rows of our table -->
    <tr id="template_table_row">
      <!-- A blank row that we'll copy to make our actual rows. -->
      <td class="name_cell">Name goes here</td>
      <td class="address_cell">Address goes here</td>
    </tr>
  </tbody>
</table>

A quick note on terminolgy: there's a table in the database, and there's a table on our page. We're taking data from the former and putting it in the latter, so it can get a bit confusing. But keep that in mind: even if it's got the same data, the table on our page is a different thing from the actual table in the database. When I say "table" or "row" here, I'm referring to the one in the HTML.

Alright, now we've got a table. It has two rows: one with a header (so the user knows what our columns mean), then one that we'll copy to make our individual table rows. Let's write the JavaScript to do that:

<script>
  async function doADatabaseQuery() {
    var results = await query(sql`SELECT * FROM schools`)
    results.forEach(function(result) {
      // Make a copy of our table row.
      var row = $("#template_table_row").clone()
      // Remove the table row's id (because no two elements can have the same
      // ID)
      row.attr("id", "")
      // Add our information to the row
      row.find(".name_cell").text(result.schoolname)
      row.find(".address_cell").text(result.address)
      // Finally, we find our table and add the row into it.
      $("#table_body").append(row)
    })
    // Hide the template row. (We do this last sot hat the rows we copy
    // don't end up hidden.)
    $("#template_table_row").hide()
  }

  doADatabaseQuery()
</script>

There's a lot going on here. Let's try to break it down. Remember, the code in the forEach happens for each item we get back from the database. First, we make a copy of the table row, and put it into the variable row. We use the $ function to find our table row, then use the clone function to make a copy:

var row = $("#template_table_row").clone()

Then, we remove our the id from our copy of the template row. (If we didn't do this, our copies would have the same id, which isn't allowed.) To do this, we use the attr function, which changes the attribute of an element.

row.attr("id", "")

Next, we actually put the data we got from the database into our new table row. To do this, we first need to find the individual cells of our row. We use the find function to do this—find is basically like $, except that it looks inside another element instead of looking anywhere on the page. Also notice that we're using . instead of #. This tells jQuery to look for an element with a certain class instead of a certain id. (A class is similar to an id, but can be used multiple times on the same page. Because we'll have a name cell for each school in our list, we can't use an id.) Once we've found our cell, we use the text function to change the contents of the cell to our data (we get the data from the result variable, which we got from querying the database).

row.find(".name_cell").text(result.schoolname)
row.find(".address_cell").text(result.address)

Finally, we put our new row into the table. To do this, we find the table (well, actually the tbody, which is the part of the table that contains the actual data), and use the append function to tell jQuery to stick the row at the end.

$("#table_body").append(row)

When we're done with the loop, we tell jQuery to hide our original template row so that it doesn't show up on the page:

$("#template_table_row").hide()