{{{{ JavaScript - Input and Output }}}}

Before learning how to make the computer do something (a computer program), you need to know how to get information into the computer (input) and how to find out what the computer has done (output).
Button (input)
Alert (output)
Text boxes (input and output)
Cursor in text boxes (input) and <SCRIPT>
Text area (output)
String and new line (output)
Select (input)
Select with value (input)
Radio buttons (input)
Start of website

Alphabetical index

Summary of colours in code: green is HTML useful for JavaScript, red is JavaScript, blue is a name and everything else is grey.



Button (input)

Input can be something extremely simple, like clicking on a button. The following code should be self-evident. It doesn't actually do anything when you click on it, since you don't know how to do output yet!

<HTML>
<HEAD>
</HEAD>
<BODY>
<INPUT TYPE=BUTTON VALUE="This button does nothing">
</BODY>
</HTML>




Alert (output)

This code has a similar button, but adds an ONCLICK to say what happens when you do click on it. The content of the ONCLICK is a bit of JavaScript - an Alert box. Click on the button to see what it looks like - I'm sure you'll recognise it! Please be careful of the quotes. Note that the ONCLICK uses double quotes, and the alert uses single quotes. You can have them the other way round if you like, but you must use both types, and one type must be inside the other type, or the poor computer will get very confused as to where the contents begin and end. Be careful with brackets as well. Every open bracket requires a closed bracket. Brackets are one of the most frequent causes of JavaScript code not working. You will see that I tend to use upper case for HTML. I do this so I can disentangle it form the content of the webpage that you see on the screen. However, the alert is lower case, as this is JavaScript, and JavaScript commands must be lower case.

<HTML>
<HEAD>
</HEAD>
<BODY>
<INPUT TYPE=BUTTON VALUE="Click here" ONCLICK="alert('Please do not click on this button again!')">
</BODY>
</HTML>

Alert boxes are not generally used for JavaScript output, since you need to click on them to make them go away. But they are very useful, especially for debugging a program (trying to find out why it doesn't work). You can put one in at any point in the program to print out anything you want (to see if it is what it should be), or even, in extreme cases, whether you ever get to that point of the program! They are also useful for error messages. For example, you may want to tell the user that the input he has entered is wrong in some way - perhaps too big or too small.



Text boxes (input and output)

Text boxes are a simple way to enter data into your program (input), and you can display the results as well (output). In this example, if you type a number into the first box, the computer assumes that it is inches, converts it to centimetres for you, and puts this value in the second box.

This coding introduces names. Names in Javascript can be upper or lower case, but whatever you use for one particular name, you must carry on using the same for that name. JavaScript is fussy about this, unlike HTML. I always use lower case so I don't keep having to remember which I've used. The text boxes are inside a FORM, which can contain ordinary HTML text as well, such as "Enter Inches" or even HTML commands. The ACTION="#" in the FORM can be left out but you're supposed to put it in to conform to standards. The FORM has the NAME convert. This gets used later, inside ONKEYUP. When using names, make sure that you don't use any JavaScript command by mistake. If you used alert, for example, it might confuse the computer as to whether you were using a name or a command. Apart from this, try to think up sensible names. It will make your code easier to understand, and that makes it easier to write and get working.

The INPUT TYPE is now TEXT (rather than BUTTON as in the previous examples). The text box also has a name, so that when you are using the value, it knows which text box you're talking about. The second box is the output box. DISABLED means that the user cannot type into it, although the program can put something in it OK. The first box is the input box, so you need to tell the computer what to do if anyone enters anything. This is done with ONKEYUP which means that the computer does something whenever you type a single key into the box (this has the rather strange effect that if you enter more than one digit, it keeps recalculating the figure for each new digit.) The content of ONKEYUP is JavaScript - document refers to this current webpage, convert to the form name, ins or cms to the text box name and value means the contents of the box. All these should have dots (or full stops) between them. The * (asterisk) means multiply by. This is a common symbol in programming languages. After all, if you used x, the computer might think you meant the letter! So the contents of the second box are set to the contents of the first box times 2.54.

Enter Inches

centimetres
<HTML>
<HEAD>
</HEAD>
<BODY>
<FORM ACTION="#" NAME="convert">
Enter Inches
<INPUT TYPE=TEXT NAME="ins"
    ONKEYUP=" document.convert.cms.value = 2.54 * document.convert.ins.value" >

<BR><BR>
<INPUT TYPE=TEXT NAME="cms" DISABLED>
centimetres
</FORM>
</BODY>
</HTML>


You might have noticed that I have put some spaces in the JavaScript, and put the second half of the INPUT statement on a second line, indenting it a little. JavaScript, like HTML, is very tolerant of spaces and new lines in its commands. You could run all the HTML and JavaScript together without any new lines at all, but it is sensible to lay out your code so it is easy to read. It makes it much easier to spot any mistakes you make. Oh yes - you will make lots of mistakes!

You may get some strange answers using the above code. If you type a letter, it says "NaN" which means "Not a Number". If you type "1.1" it says "2.7940000000000005". See types of data for an explanation and how to avoid this problem.



Cursor in text boxes (input) and <SCRIPT>

There is a problem with the code above. You have to click on the inches box before typing anything into it, to move the cursor. While you are probably used to doing this is webpages, wouldn't it be nice if we could set the cursor up to appear automatically in the right box! This is what the code below does.

To set up the cursor, you need a piece of JavaScript. However, this must appear in the main part of the HTML, not as part of ONKEYUP. The code in ONKEYUP is only run when (and if) you type something into the box. But you want the cursor to appear before you start typing, in fact, when the webpage is first loaded. If you have some JavaScript in the main part of the webpage, you need to tell the HTML that it is JavaScript. You do this by surrounding the JavaScript with <SCRIPT> (saying what type of script it is) and </SCRIPT>. You can leave the TYPE out, but you're supposed to put it in to conform to standards. This piece of JavaScript follows the HTML for the FORM. If you put it before the FORM, then the computer doesn't know what you're talking about! The JavaScript needs to specify which text box you want the cursor in, and .focus() tells the computer that you want a cursor in it.

This code converts Fahrenheit to Celsius, so I've changed all the names so they make sense. I've also specified SIZE for the text boxes. This gives the size of the box, if you don't like the default. The user will be able to type in a longer piece of data, but it will move along the box (you're probably used to seeing this on websites). If you want to stop the user from typing in too long a piece of data, specify MAXLENGTH=.

You will also see some more arithmetic symbols. Subtract is - and divide is / and you can use brackets. You convert from Fahrenheit to Celsius bu subtracting 32, and multiplying the result by 5/9.

There isn't the example of this code on this webpage, as it messed things up! Look at the example webpage to see it in action.

<HTML>
<HEAD>
</HEAD>
<BODY>
<FORM ACTION="#" NAME="temp">
Enter Fahrenheit
<INPUT TYPE=TEXT NAME="fahr" SIZE=3
ONKEYUP="document.temp.cels.value = (document.temp.fahr.value - 32) * 5 / 9">

<BR><BR>
<INPUT TYPE=TEXT NAME="cels" SIZE=3 DISABLED>
Celsius
</FORM>
<SCRIPT TYPE="TEXT/JAVASCRIPT">
document.temp.fahr.focus()
</SCRIPT>
</BODY>
</HTML>




Text area (output)

INPUT=TEXT will only give you one line of text.You can specify a TEXTAREA instead, which allows you to have several lines of text. Note that you have a <TEXTAREA..> and </TEXTAREA> with the initial value of the text area between. Anything you type into the box is ignored, as there is no ONKEYUP. I've left out DISABLED as it comes out grey! This means that people can type into the box if they want, but nothing would happen, of course. Put DISABLED in if this worries you. You can of course have an input TEXTAREA with ONKEYUP. This mans that people can type in more than one line of code.
By the way, the poem is the first verse of Jabberwocky, by Lewis Carroll.

<HTML>
<HEAD>
</HEAD>
<BODY>
<FORM ACTION="#">
<TEXTAREA COLS=36 ROWS=4>

`Twas brillig, and the slithy toves
Did gyre and gimble in the wabe:
All mimsy were the borogoves,
And the mome raths outgrabe.
</TEXTAREA>
</FORM>

</BODY>
</HTML>




String and new line (output)

This mostly uses code that you should recognise already, but arranged in a different way. The previous examples are a bit irritating because the answer keeps changing as you type more digits. This is because I used ONKEYUP, so every time you use a key, it recalculates the answer. There are other options. Try replacing ONKEYUP by ONBLUR in one of the examples above and see what happens. You don't get the answer when you type the digits. Instead, you have to click somewhere else on the page (anywhere, it doesn't matter), or use the Tab key to get the answer. Unfortunately, Enter doesn't do it! This is also an unsatisfactory solution, so this code below gives another option.

It gives a button as well as the two boxes. You type in the data, a temperature in Celsius this time. When you have finished the number, you click on the button marked "Convert to Fahrenheit". The input and the answer appear in the text area. Note that this time the JavaScript which calculates the answer does not appear in the text area code, but in the button code. This is because the button calculates the answer. I haven't specified the cursor in this example, as it messes up this webpage. See this example instead.

Instead of just giving the answer as a number, I have formatted it as a string. A string is a collection of words and possibly numbers. This makes the ONCLICK rather long. When you code this, you don't need to lay it out as elaborately as I have, but I wanted to make it absolutely clear to you. The different parts of the string are joined together with +. We start with the input value, then some text ('degrees Celsius' and so on), then the calculation of the answer, then some more text. One of the pieces of text looks rather strange, '\n'. This puts in an end of line, so the answer appears on two lines.

You may notice that the calculation of the answer uses + to mean add two numbers together. So how does the computer know when + means add, and when + means join two strings together? Well, if you have two numbers either side of the +, it reckons that you want them added. If one or both are text (letters or words), then it thinks you must mean join two strings. It usually gets it right! You can see that I put the calculation in brackets, just in case.

Enter Celsius



<HTML>
<HEAD>
</HEAD>
<BODY>
<FORM ACTION="#" NAME=temp>
Enter Celsius
<INPUT TYPE=TEXT NAME="cels" SIZE=3>
<BR><BR>
<INPUT TYPE=BUTTON VALUE="Convert to Fahrenheit"
ONCLICK="document.temp.fahr.value
  = document.temp.cels.value
  + ' degrees Celsius'
  + '\n'
  + 'is '
  + ((document.temp.cels.value * 9 / 5) + 32)
  + ' degrees Fahrenheit'
">

<BR><BR>
<TEXTAREA NAME=fahr COLS=30 ROWS=2 DISABLED>
</TEXTAREA>
</FORM>

</BODY>
</HTML>




Select (input)

One problem with text boxes as input is that the user can type any old rubbish into them. Try typing letters into the conversion programs above, for example. Once you starting writing proper JavaScript code (which we haven't got onto yet), then you can check that the input is roughly what you expect, and produce error messages if it isn't. However, if you have a very limited range of valid inputs, then use SELECT, as below.

You define a list of options. Here I have used the numbers from zero to five, but they could be words describing options or anything else. In each SELECT, one of the options is SELECTED. This means that this option shows in the box at the start. Click on the little arrow and you will see there are numbers above it as well as below it. ONCHANGE contains some JavaScript which will happen whenever the user selects a different option. Note that nothing happens before an option is selected, or if the same option is selected again. There are a couple of ways of using the option that has been selected. In this code, I use .selectedIndex for each SELECT. The stuff in front tells you which SELECT it is, like the .value used in the examples above. .selectedIndex gives the position in the list. However, computer people tend to count from zero, so the first option in the list has .selectedIndex of zero, the second option is 1, and so on. Since I carefully chose my numbers to have the same value, this means that if you select a number, you get an answer of that multiplied by the other number. SELECT code is often quite long, so I've only done numbers up to 5. If you want a version which goes up to 10, see this example.

multiplied by =
<HTML>
<HEAD>
</HEAD>
<BODY>
<FORM ACTION="#" NAME=times>
<SELECT NAME="num1" ONCHANGE="document.times.answer.value
  = document.times.num1.selectedIndex * document.times.num2.selectedIndex
">
<OPTION>zero</OPTION>
<OPTION>one</OPTION>
<OPTION SELECTED>two</OPTION>
<OPTION>three</OPTION>
<OPTION>four</OPTION>
<OPTION>five</OPTION>
</SELECT>

multiplied by
<SELECT NAME="num2" ONCHANGE="document.times.answer.value
  = document.times.num1.selectedIndex * document.times.num2.selectedIndex
">
<OPTION>zero</OPTION>
<OPTION>one</OPTION>
<OPTION SELECTED>two</OPTION>
<OPTION>three</OPTION>
<OPTION>four</OPTION>
<OPTION>five</OPTION>
</SELECT>

=
<INPUT TYPE=TEXT NAME="answer" SIZE=2 DISABLED>
</FORM>

</BODY>
</HTML>




Select with value (input)

Using the index number of a SELECT can be cumbersome, even if you do remember that it always starts at zero! Another way of using a SELECT statement is to use VALUE. This goes inside every <OPTION>. In this example, the SELECT list contains Latin phrases, and the VALUE in each case contains the English translation. ONCHANGE contains the necessary JavaScript code to display the output (the English translation) - I've made it an alert box because I was getting bored with text boxes! Probably a text box would have been more sensible.

You can see that I have made the first line of the SELECT "- Select a Latin phrase -". This is often done. It means that you have told the user what to do, and also you force at least one select before something happens. If I hadn't done that, then it would show "In vino veritas", and the user might want to know why it hadn't been translated. The reason would be, of course, that the output only happens when the SELECT box is changed. Nothing happens when you first see it. If you are using the index feature of SELECT instead, then the first line is index zero, and if you prefer your index to start at one for your useful data, then making the first line into an instruction rather than a data choice is also helpful. But remember that the user can always select the first line. Try it with this example. Select a Latin phrase, then select the "- Select a Latin phrase -" and see what happens. By the way, the example webpage has more Latin phrases to choose from.

<HTML>
<HEAD>
</HEAD>
<BODY>
<FORM ACTION="#" NAME=latin>
<SELECT NAME="words" ONCHANGE="alert(document.latin.words.value)">
<OPTION VALUE="- Select a Latin phrase -">- Select a Latin phrase -</OPTION>
<OPTION VALUE="Truth in wine">In vino veritas</OPTION>
<OPTION VALUE="Art for art's sake">Ars gratia artis</OPTION>
<OPTION VALUE="I think therefore I am">Cogito ergo sum</OPTION>
<OPTION VALUE="I came, I saw, I conquered">Veni, vidi, vici</OPTION>
<OPTION VALUE="Beware of the dog">Cave canem</OPTION>
</SELECT>
</FORM>

</BODY>
</HTML>




Radio buttons (input)

Radio buttons are another way of selecting an option. You've probably seen them in other people's webpages. The choice of SELECT or RADIO is up to you - it's just a matter of presentation. The RADIO options are visible on the webpage without using a drop-down menu. They can be useful if you only have a few options. If there are lots of options, using RADIO would take up too much room on your webpage, and SELECT would be better.

You need an input statement for each option of the RADIO (as opposed to one SELECT statement with several OPTIONS). The INPUT statements are tied together by having the same NAME, in this case "today". The last INPUT statement is not part of the Radio buttons as it has a different NAME, and also its TYPE isn't "radio". When you click on one of the radio buttons, a dot appears in it, and disappears from the previous one. Also the JavaScript code in ONCLICK gets actioned. Here, I have used some JavaScript commands which will give you today's year, month or day. The JavaScript month starts from zero, rather than 1 as we are used to, so I add 1 to the month to make it easier to understand.

The first INPUT statement has CHECKED in it. This means that the dot will start off in the first button. You could put CHECKED on one of the other buttons instead if you wished. However, putting CHECKED does not action the code to start with. So you will get the first button with a dot in it, but nothing in the output text box. To avoid this, I have added a SCRIPT after the definition of the Radio buttons, which gives a start value to the output. It does mean that you have to code that JavaScript code twice.

Year
Month
Day of month

<HTML>
<HEAD>
</HEAD>
<BODY>
<FORM ACTION="#" NAME=date>
<INPUT TYPE="radio" NAME="today" CHECKED
  ONCLICK="document.date.show.value=new Date().getFullYear()">Year
<BR>
<INPUT TYPE="radio" NAME="today"
  ONCLICK="document.date.show.value= (new Date().getMonth()) + 1">Month
<BR>
<INPUT TYPE="radio" NAME="today"
  ONCLICK="document.date.show.value= new Date().getDate()">Day of month
<BR><BR>
<INPUT TYPE=TEXT NAME="show" SIZE=4 DISABLED>
</SELECT>
</FORM>

<SCRIPT TYPE="TEXT/JAVASCRIPT">
document.date.show.value=new Date().getFullYear()
</SCRIPT>
</BODY>
</HTML>


Return to JavaScript index



Valid HTML 4.01!

© Jo Edkins 2005