Chapter 1 deck Chapter 2 deck Chapter 3 deck Chapter 4 deck Chapter 5 deck Chapter 6 deck Chapter 7 deck Chapter 8 deck Chapter 9 deck Chapter 10 deck Chapter 11 deck Chapter 12 deck Chapter 13 deck Chapter 14 deck

onLoad, Radio Buttons & JS Event Properties

5 slides · use ←/→ or Space to navigate, F for fullscreen.

Reading view

← Back to the full Chapter 6 deck

onLoad, Radio Buttons & JS Event Properties
Fullscreen for presentation · Print / PDF for a handout
1 / 5
Lesson

onLoad, Radio Buttons & JS Event Properties

Page-load handlers, reading radio button groups, and assigning handlers to JS properties.

onLoad, Radio Buttons & JS Event Properties

The onLoad Event — Page Load Handler

Triggered when the loading of a document is fully completed. Ideal for running initialisation code after the page is ready.

<html>
<head>
  <script>
    function load_greeting() {
      alert("Welcome to Pete's Pickled Peppers!");
    }
  </script>
</head>
<body onload="load_greeting()">
  <!-- The greeting fires as soon as the page finishes loading -->
</body>
</html>
onLoad, Radio Buttons & JS Event Properties

Event Handling — Radio Buttons

  • All radio buttons in a group share the same name attribute.
  • You cannot identify the selected button by name — use the checked property.
  • Iterate over the form's elements array to find the checked radio button.
var radioElements = document.myForm.elements;
var selected = "";

for (var i = 0; i < radioElements.length; i++) {
  if (radioElements[i].checked) {
    selected = radioElements[i].value;
    break;
  }
}
onLoad, Radio Buttons & JS Event Properties

Assigning Event Handlers to JavaScript Properties

  • Property names are lowercase versions of the HTML event attributes.
  • Assign the function name (not a call) to the property.
  • The handler can be replaced or removed at runtime.
  • Limitation: no way to pass parameters to the handler function.
// Assign a handler to the first form element
document.myForm.elements[0].onclick = myHandler;

// For a radio button group — assign to each element
var els = document.myForm.elements;
for (var i = 0; i < els.length; i++) {
  els[i].onclick = myHandler;
}
onLoad, Radio Buttons & JS Event Properties

Activity — complete the code

Complete the page-load handler and radio button loop.

<!-- Fires when the document has fully loaded -->
<body ="load_greeting()">
 
<!-- Radio buttons share a name; use the checked property -->
var els = document.myForm.;
for (var i = 0; i < els.length; i++) {
if (els[i].) {
selected = els[i].value;
break;
}
}
 
// Assign a handler to a JS property (no parentheses)
document.myForm.elements[0]. = myHandler;