The use of HTML elements such as buttons, dropdown menus, check boxes and other features are essential when planning and building a website.
JavaScript has several ways to communicate with these elements in order to perform tasks.
Buttons are the simplest elements in HTML. To create a button use the following line of code within the body of your HTML.
<button type="button">BUTTON</button>
However this button will not perform any action. Adding an onclick
event to the code will tell the button to perform an action when it is clicked. Use the following line of code to create a "hello world" popup.
<button type="button" onclick="alert('Hello world!')">BUTTON</button>
Click on the button below to see it in action...
You can also attach onclick
to images to make buttons, thus:
<img src="images/circle.gif" onclick="alert('Hello Chigwell Row!')"></img>
Here it is in action. We've used a gif with the outside set to be transparent so the background shows through and makes it circular:
To create a drop down menu in HTML the following code is used in the body of the HTML.
<select>
</select>
This code gives:
i.e. a blank dropdown. In order to fill it option tags must be added between the select tags.
<select>
<option value="Geog">Geography</option>
<option value="Chem">Chemistry</option>
<option value="Phys">Physics</option>
<option value="Eng">English</option>
</select>
which produces...
In order to communicate with the JavaScript the select tag must be given an ID and
an "onchange
" handler, as in the following piece of code.
<select id="department" onchange="print()">
<option value="Geog">Geography</option>
<option value="Chem">Chemistry</option>
<option value="Phys">Physics</option>
<option value="Eng">English</option>
</select>
We can then get hold of the index of the chosen option (numbered from zero); the "value
"
(e.g. "geog
"), and the text (e.g. "Geography
").
Here's a handler that shows how to do that:
function print() {
var e = document.getElementById("department");
var dropDownIndex = e.options[e.selectedIndex].index;
var dropDownText = e.options[e.selectedIndex].text;
var dropDownValue = e.options[e.selectedIndex].value;
alert(dropDownIndex + " " + dropDownValue + " " + dropDownText);
}
And here it is as a webpage.
Have a play around with these in a new web page, or maybe use some of these elements for your assessments!