JavaScript

Selects and Options

A longstanding popular effect in forms are multiple selects – your choice in one select element (for example, a country) will cause a second select element to display a different list of options (states or counties).

The update of the second element is done using JavaScript:

var states = [];
var states[0] = ['South Australia', 'New South Wales']; // Australia
var states[1] = ['Cumbria', 'Berkshire'];  // United Kingdom
 
function change_state_select()
{
  var nation_select = document.getElementById('nation_select');

Lessons Learned: Cross-platform JavaScript

One area where I regularly hit a wall is when using JavaScript. Documentation on the various browsers' support of JavaScript and the Document Object Model (the DOM - a way of interacting with the various elements within a document in a logical fashion) is not always well documented. Sometimes the information is there, but it takes a lot of digging, and other times it's just time to try and learn by finding what works.

Working with Tables

FireFox lets you add rows to a table simply by using the innerHTML property of the table object:

function addRow()
{
 
  var table = document.getElementById('data_table');
 
  table.innerHTML += '<tr>';
  table.innerHTML += '<td>Cell 1</td>';
  table.innerHTML += '<td>Cell 2</td>';
  table.innerHTML += '</tr>';
 
}

<table id="data_table">
  <tr>
    <td>Cell 1</td>
    <td>Cell 2</td>
  </tr>
</table>
 
<p>
  <button type="button" onclick="addRow()">Add a Row</button>
</p>

Controlling CSS Attributes

I was writing some JavaScript functions to react to onclick events which changed the background and text colours of a number of elements. Because I wanted “unselected” elements to return to a normal state, I had used the following JavaScript:

var selected_element_id = null;
 
function select_element(element_id) {
 
  var element = document.getElementById(element_id);
 
 
  if (element_id == selected_element_id) {
 
    selected_element_id = null;
 
    element.style.color = "inherit";  // set the text colour to match the parent's setting