04 Buttons & Functions

Add the following code to a new web page:

<script language="JavaScript">function op(){

document.write ("Making buttons using Javascript is easy. Just like the text field we used in chapter 1, a button needs to be a part of a form. Click the Back button to continue")

}

</script>

<form action="" method="post" name="form1">

<p>

<input type="button" name="button1" value="Hello" onclick="op()"

align="center"></form>

</p>

The document.write is contained in a 'function'. The button displays the 'value'. The code in the function is called with the 'onclick' component of the button.

Notice the {} brackets enclose the entire function which can be any number of lines of code containing nested loops and even calls to other functions. In this case the function name is op and the brackets (), for now, are left empty.

Review

    • buttons need to be a part of a form

    • ordinary buttons are of type "button"

    • pay attention to the quotes after onclick

    • buttons can be used to "call" JavaScript functions

    • JavaScript functions need to be at the top of the page

    • function code needs to be enclosed within { }

Practice

Job 41:

Make a button that calls a function. The function should generate a random number and then change the value of the button to the new number. The initial value of the button should be the word "Random".

Job 42:

Make up a Dungeons and Dragons web page. In the Dungeons and Dragons game players battle and win or loose depending on the outcomes of multisided dice. Players compare their "abilities" and "weapons" to determine the odds. Different multisided dice are used to allow opponents to roll or "battle" according to the odds. Your page should allow players to generate random rolls for dice that are 4, 5, 6, 7, 8, 10, 12, 15, 18, 20, 24 and 28 sided.

Here is the solution to job 41.

Here is another example of a webpage with buttons and text boxes and a script that adds two numbers together with an onclick() event.