Wednesday, October 15, 2014

JavaScript Tutorial – Lesson 5 Part 2

JavaScript Tutorial – Lesson 5 Part 2


Contents


  1. Text Field Exercise
  2. Checkboxes
  3. Radio Buttons
  4. Selects
  5. onChange in Select Form Elements

Text Field Exercise

This exercise is an extension of one we did in Lesson 4. The exercise is to get this textarea to behave like a browser’s Location box. If you type in http://www.webmonkey.com/ or just www.webmonkey.com, it’ll spawn a window that displays the Mattmarg.com Web site.
Try getting this to work before viewing source to see a solution. When you’re done, it’s time to move on to checkboxes and radio buttons.

Checkboxes

Text fields and textareas are just two types of form elements. Others that we’ll look at in this lesson are checkboxes, radio buttons, and selects. Let’s discuss checkboxes first.
Checkboxes have one main property of interest: checked.
If you have a form named the_form and a checkbox named the_checkbox you can see if the checkbox has been checked like this:
01var is_checked = window.document.the_form.the_checkbox.checked;
02
03 if (is_checked == true)
04
05 {
06
07   alert("Yup, it's checked!");
08
09 else {
10
11   alert("Nope, it's not checked.");
12
13 }
As you can see, if a checkbox is checked, the checked property will be truetrue is a built-in JavaScript datatype, so you don’t have to put it in quotes when checking it. If the checkbox is not checked, the checked property will be false (also a built-in datatype).
Just like you can read the checked property, you can set the checked property. Here’s an example of checking and setting the checked property of a checkbox.
Here’s the code for the above:
01<form name="form_1">
02
03 <input type="checkbox" name="check_1">Checkbox 1
04
05 </form>
06
07 <a href="#" onClick="window.document.form_1.check_1.checked=true;
08
09 return false;">Click to check Checkbox 1</a>
10
11 <a href="#" onClick="window.document.form_1.check_1.checked=false;
12
13 return false;">Click to uncheck Checkbox 1</a>
14
15 <a href="#" onClick="alert(window.document.form_1.check_1.checked);
16
17 return false;">Click to see the value of Checkbox 1</a>
Notice that I’m sticking the return false in the href. It stops the page from bouncing around when you click on a link.
Checkboxes have one interesting event handler:onClick. When someone clicks on a checkbox, the onClick event handler goes into action. Here’s an example of it in use.
This example introduces a few new things. First, there’s form that introduces the onClick checkbox handler:
1<form name="form_2">
2
3 <input type="checkbox" name ="check_1"
4
5 onClick="switchLight();">The Light Switch
6
7 </form>
When someone clicks on the checkbox, the onClick handler gets triggered and executes the switchLight() function. Here’s the switchLight() function (it’s in the header of this page):
01function switchLight()
02
03 {
04
05   var the_box = window.document.form_2.check_1;
06
07   var the_switch = "";
08
09   if (the_box.checked == false) {
10
11     alert("Hey! Turn that back on!");
12
13     document.bgColor='black';
14
15   else {
16
17     alert("Thanks!");
18
19     document.bgColor='white';
20
21   }
22
23 }
The interesting thing here is the first line:
1var the_box = window.document.form_2.check_1;
This line assigns the checkbox object to a variable. This a handy way to cut down on your typing. It’s also a good way to pass objects as parameters to functions. We’ll see a lot more of that in later lessons.
That’s most of what you have to know about checkboxes. Now let’s learn about radio buttons.

Radio Buttons

Happily, radio buttons are almost exactly like checkboxes with respect to JavaScript. The only real difference is in the HTML. Checkboxes are on/off devices. If a checkbox is checked, you can uncheck it. If it’s unchecked, you can check it. Radio buttons are different. Once a radio button is on, it stays on until another one is selected. Then the first one goes off. Here’s a typical radio button set:
As you can see, you can’t simply unselect a radio button, you have to choose a new one. With that in mind we can re-do the light switch example with two radio buttons instead of one checkbox:
This example looks very much like the checkbox example. The form is:
1<form name="form_1">
2
3<input type="radio" name ="radio_1" onClick="offButton();">Light off
4
5<input type="radio" name ="radio_2" onClick="onButton();" checked>Light on
6
7</form>
When the first radio button is clicked, the offButton() function is called. That function is:
01function offButton()
02
03 {
04
05   var the_box = window.document.form_1.radio_1;
06
07   if (the_box.checked == true)
08
09   {
10
11     window.document.form_1.radio_2.checked = false;
12
13     document.bgColor='black';
14
15     alert("Hey! Turn that back on!");
16
17   }
18
19 }
This is pretty much just like the checkbox example earlier. The main difference is this line:
1window.document.form_1.radio_2.checked = false;
This tells JavaScript to turn off the other button when this button has been clicked. The function that is run when the other button is clicked is similar to this one:
01function onButton()
02
03{
04
05  var the_box = window.document.form_1.radio_2;
06
07  if (the_box.checked == true) {
08
09    window.document.form_1.radio_1.checked = false;
10
11    document.bgColor='white';
12
13    alert("Thanks!");
14
15  }
16
17}
There are a few more details about checkboxes and radio buttons, but those can wait until the next set of tutorials. Right now, let’s look at the last type of form element, selects.

Selects

Selects are the strangest of the form elements we’ll cover in this lesson. There are two primary kinds, pulldown selects and list selects. Here are examples of each:
The thing that makes select objects strange is that the whole select is named, but none of the select’s options is. For example, the HTML for the first select looks like this:
01<select name="pulldown_1" size=1>
02
03<option>probiscus
04
05<option>spider
06
07<option>lemur
08
09<option>chimp
10
11<option>gorilla
12
13<option>orangutan
14
15</select>
Notice that the whole select is named pulldown_1, but the individual options aren’t named. This makes it difficult to access individual options.
Luckily, through the magic of arrays and objects, there’s a way to access and change the options of a select. If you wanted to change the second option of the pulldown menu, you’d type:
1window.document.form_1.pulldown_1.options[1].text = 'new_text';
This works because the select element has an options property that is an array of all the select’s options. You can grab one of the options in the array and change its text property. Try it – change the select and then scroll up to see that the pulldown menu actually changed. The second option in the pulldown select should now be *thau*.
In addition to the options property, selects have a property called selectedIndex. When one option in a select has been chosen, the selectedIndex property of the select will be the array number of the selected option. To test this, select one of the options in the list select (the second one) and then check the index. Remember that the first option in the array is option 0. The line I used to check this was:
1<a href="#" onClick="alert('index is:' + window.document.form_1.list_1.selectedIndex); return false;">check the index.</a>
The form is named form_1, the list select is named list_1. To get the selectedIndex, I looked at window.document.form_1.list_1.selectedIndex. If you want, you can set the selectedIndexlike this …
1window.document.form_1.list_1.selectedIndex = 1;
…. and highlight the second option in the list_1 select.
Once you know the index number of the selected option, you can find out what it is:
1var the_select = window.document.form_1.list_1;
2
3var the_index = the_select.selectedIndex;
4
5var the_selected = the_select.options[the_index].text;
The selectedIndex property is great when you only have one option selected. What happens when you have more than one option selected? Well, that gets slightly stranger. If you want to know, here’s some information about multiple selects.
Just like the other form elements, the select element has a handler:onChange(). This handler gets called whenever there’s a change to the select. Here’s the example from Lesson 1 to show you how  onChangeworks with a select.

onChange in Select Form Elements

Play with this example and then read the blow-by-blow description.
This is a fairly complicated JavaScript, so let’s go through it slowly. First, let’s look at the form itself (notethat your browser might wrap that onChange line, but it should be on one line, no spaces, inyour code):
01<form name="the_form">
02
03<select name="choose_category"
04
05  onChange="swapOptions
06
07  (window.document.the_form.choose_category.
08
09  options[selectedIndex].text);">
10
11<option selected>Dogs
12
13<option>Fish
14
15<option>Birds
16
17</select>
18
19<select name="the_examples" multiple>
20
21<option>poodle
22
23<option>puli
24
25<option>greyhound      .
26
27</select>
28
29</form>
This form has two elements, a pulldown select and a list select. The pulldown select has an onChangehandler that calls a function called swapOptions()swapOptions(), which is defined in the header, has one parameter – the selected animal type.
Now let’s check out the header. The first thing that happens is I define a few arrays:
1var dogs = new Array("poodle","puli","greyhound");
2
3var fish = new Array("trout""mackerel""bass");
4
5var birds = new Array("robin""hummingbird""crow");
Notice that the arrays are named the same thing as the animals in the pulldown select. You’ll see why soon. Now let’s look at the function that gets called when the pulldown select is changed:
01function swapOptions(the_array_name)
02
03{
04
05  var numbers_select = window.document.the_form.the_examples;
06
07  var the_array = eval(the_array_name);
08
09  setOptionText(window.document.the_form.the_examples, the_array);
10
11}
The function definition includes one parameter:the_array_name. If you pulled the pulldown select to “Fish,” the_array_name will equal the string “Fish.”
The first line in the body of the function sets a variable to refer to the second form element, the list select.
The second line introduces something new:eval()eval() is a little weird and better left for later lessons. The end result of the second line is that the variable the_array will equal one of the arrays defined earlier. If the_array_name is “Fish,” the_array will equal the Fish array. If you want a description of how this happens, study up on eval.
The third line of the function calls another function called setOptionText()setOptionText() does the work of setting the values of the list select to the contents of the_array. Here it is:
01function setOptionText(the_select, the_array)
02
03{
04
05  for (loop=0; loop < the_select.options.length; loop++)
06
07  {
08
09    the_select.options[loop].text = the_array[loop];
10
11  }
12
13}
This function takes two parameters, a reference to a select element and an array. The first line of the function sets up a for loop, which loops through all the options in the select element. Remember that the options property of a select element is an array of all that select’s options. Because it’s an array, you can find out how many options are in a select using the length property of arrays. That’s how the loop works.
The first time you hit the loop, the loop variable equals 0. The body of the loop then reads:
1the_select.options[0].text = the_array[0];
If you chose “Fish” in the pulldown, the_array[0] will be “trout,” so this line will change the first option in the list select to “trout.” The next time through the loop, loop will equal 1, and the second option in the list select will equal “mackerel.”
There’s one caveat to all this. When you change the text of an option, the size of the select won’t change. So if you change an option’s text to something really long, it’ll probably get cut off.
One way to get around this is to stretch out the select when you first go to it. For example, I did this:
1<option>greyhound      .
Note the period I used to stretch out my select box. It’s sort of cheesy, but it works.
OK, that was a mouthful. If you understand how this example works, you understand a lot of JavaScript, and you’ll have no problem doing your homework assignment for this lesson. Once you’ve done the example and viewed source to see how I did it, go on to this lesson’s review.

No comments:

Post a Comment