JavaScript - Lesson 7, Input ControlsLearning Objectives
So far, the only way we have found for getting data into a JavaScript program has been the prompt() function. This is a clumsy way of doing it - the dialog box appears immediately that the page has been loaded, usually on top of some vital screen data (although there is nothing to stop you moving it around), and the only way to get rid of it is either to enter some data or click on Cancel. Wouldn't it be nice if we could include those small grey icons (often termed "buttons") and check boxes that you see on proper web sites! Well, this is easily achieved by including a form in a web page. A form includes several elements, each of which is a button, check box or a small slot for entering text. Furthermore, we can link each of these elements with its own piece of JavaScript code, so that when the element is clicked on, JavaScript does something. This time it is the user, not the program, that decides when data is passed to the program, and in what order. The <form> tagThis first part is not really JavaScript, it is HTML, but as you should know by now, JavaScript and HTML are intimately linked, so bear with me. The <form> tag is terminated by </form> and contains as much plain text and HTML as you like (tables, images, hyperlinks - whatever you like!) However, it also contains input tags, which usually take the form of <input> followed by </input> <form name="myForm" id="myForm"> Here is some text, and HTML tags <img src=mypic.gif alt="My picture" /> ... etc. <input name="element1" id="element1" type="button" value="Click on me!" onclick="func1();"> </input> Some more text and HTML if you want it! <input name="typeInMe" id="typeInMe" type="text"></input> I have put in some more HTML <hr /><p /> etc. </form> Would you like to see what that form looks like? Here it is. Feel free to type in the text box and click on the button if it gives you a thrill: All the items are strung together on one line as I didn't include any line breaks in the form definition (silly me!). Ignore the lines where I have put in random text and HTML - this was just to prove that I could. Concentrate on the <form> and <input> tags. Note that the <form> has been given a name using the name= attribute. This is so that JavaScript will be refer to it. However, some browers require an id= attribute instead of name=, so I have duplicated the name in this. If you are unsure which browser will be used to display your page (and that applies to just about every web page in the world!) then include both name= and id= with the same value following them. I have included two input elements, each named in a similar way to the form. The first is a button (as shown by the attribute type="button") and the caption that appears on the button is Click on me! (as shown by the attribute value= which, for button inputs, specifies what caption appears on the button). The second control is an input slot (suitable for typing in text), as shown by the attribute type="text". It has a name, but not a value= attribute. These are only two types of the elements that you can include within forms - I shall describe a few more later! The concept of eventsYou will notice that there is one part of the form that I didn't explain - the onclick= attribute. This is what we call an event handler. An event is a rather grand word describing the most mundane happenings - when the user clicks a mouse on something, scrolls the web page up or down, moves from one page to another, or types some text into an input slot - these are all events.
When an event happens, we want it to cause some action to take place, so we add an event handler. In the case of that button in the form above, we want the button to react to the user clicking the mouse on it, the click event. The attribute onclick= is followed by one or more JavaScript commands (complete with semicolon at the end) enclosed within quotation marks. Here is an example of an input element: <input id="x" name="x" type="button" value="Click on me!" onclick="var a = 3; alert('a is ' + a);"></input> (I have included that example on the left. The button is that small grey slab with the caption "Click on me!". Go on, give it a click!) You will notice that I have included both the name= and the id= attributes - I tend to (unless I forget!) The caption on the button is given by the value="" attribute. If you miss this attribute out, you just get a small grey rectangle, like this: In this case, when the button is clicked on, the instructions that are carried out are var a = 3; alert('a is ' + a); (You will notice that single quotation marks within the alert() instruction as the whole thing is enclosed within double quotation marks - and we don't want JavaScript getting confused! Most of the time the onclick= attribute is given a function call within the quotation marks, as a function can include as many characters as you like. For instance, if you had an input element defined like this: <input id="enterDetails" name="enterDetails" type="button" onclick="trapDetails();"> </input> You could then include the following function definition inside your JavaScript program: <script language="JavaScript"> function trapDetails () { // Put in here all the things that you want to happen // when the user clicks on the enterDetails button } </script> Reading values from input elementsSo, we now know how to activate a function when a button is clicked on. What about reading text from input elements? Forms are objects within the JavaScript program - they contain their elements as properties. The elements inside the forms are themselves objects, and they contain properties such as their value etc. For instance, consider that form above called myForm. This contained two input elements, one a text box and the other a button. If you are using Internet Explorer, the easiest way to read the text entered by the user into the box is as follows: myForm.typeInMe.value It can be read just like a normal variable: var textEntered = myForm.typeInMe.value; if (textEntered == "hello") document.write("Well done. You typed the magic word!<P>"); In fact, we can also access the value property of the other input element - although we already know what this will be as it matches the caption of the button. Of course, there is no reason why we can't alter the caption on the button to anything else: myForm.element1.value = "Click on me or else!"; Similarly, you can alter the value property of the text box, which will change the text written in the text slot. Please note the full stops (periods) between the objects and their properties - these are exactly the same as the full stops that separate the words document and write in the document.write() command that you met in the first lesson. Other browsers may not recognise the code if you arrange it like that, however (I know Firefox has a problem with it!) In this case, there is a general method (available in Internet Explorer as well) called getElementById that accesses any named item on a web page (i.e. any item with a name= and/or an id= attribute. Here's how you would use it: var textEntered = document.getElementById("typeInMe").value; if (textEntered == "hello") document.write("Well done. You typed the magic word!<P>"); This looks a little peculiar as you have got a method call followed immediately by a dot. However, all document.getElementById("typeInMe") does is the equivalent of myForm.typeInMe - it retrieves the input element called typeInMe wherever it appears on the page, and the .value that follows it simply gives the value of that element. Here's the second example rewritten in a similar way: document.getElementById("element1").value = "Click on me or else!"; document.getElementById("...") is very powerful - so much so, that I might show you some of the other things it can do in a later chapter. Note with document.getElementById("...") that
Another example of a formHere is a simple form which asks you for your name and then displays a welcoming message when you click on the "Here it is" button: <form id="askName" name="askName"> Please enter your name : <input type="text" id="person" name="person" size="40"> </input> <br /><div align="center"> <input type="button" value="Here it is" onclick="say_hello();"> </input> </div> </form> <script language="JavaScript"> function say_hello () { var user = askName.person.value; // Replace the line above with var user = document.getElementById("person").value; if you want if (user == "") document.write("Ah ha! I see you are the man with no name!"); else document.write(" Work through this line by line to see how it works. I have not given the button a id="" or a name= attribute, as we don't need to refer to the button as such within the JavaScript program. The person's name is read from the text box using the var user = askName.person.value statement, or the var user = document.getElementById("person").value; statement if you prefer. The function say_hello() is called when the user clicks on the button. I have added a size= attribute to the text box to specify how wide I want it to be. size="40" means that the slot is wide enough to see 40 characters that I have typed at any point - of course, I can type more, but after 40 characters, the text will "scroll". And here's the form itself: Radio buttonsThese are nothing to do with radios. They are small circles which the user can click on to "set" them or "clear" them (i.e. to specify a yes/no option). When they are set, they are filled in black. When they are cleared, they are white. To create a radio button, use the <input type="radio"> tag. The caption to the button (i.e. the writing that goes with it), is displayed as normal text afterwards. Radio buttons are similar to check boxes (which can also be set or cleared), with one essential difference. You can group several radio buttons together (by giving them all the same name using id= or name=), in which case the user will only be able to select one of them at a time. If the user clicks on any of the buttons, then that one becomes set, and any other button that was set is cleared automatically. This is the normal way of using radio buttons: <form id="quiz" name="quiz"> <p>In which country would you find the Great Wall of China? </p> <input type="radio" id="q" name="q" onclick="guess(1);"></input> England <br /> <input type="radio" id="q" name="q" onclick="guess(2);"></input> Russia <br /> <input type="radio" id="q" name="q" onclick="guess(3);"></input> China <br /> <input type="radio" id="q" name="q" onclick="guess(4);"></input> Australia <p /> <input type="button" onclick="markAnswer();" value="Done"></input> </form> Here we have four almost identical radio buttons - each within the same form and each with the same name. They all call the same function, but they each pass a different parameter value to the function. This is how the function knows which of the buttons was selected. The function is called when any of the radio buttons is clicked. The function might be called like this: <script language="JavaScript"> var myAttempt = -1; // -1 indicates "no valid answer" function guess (value) { myAttempt = value; } function markAnswer () { switch (myAttempt) { case -1 : document.write("Ah come on! You didn't try!"); break; case 1 : case 2 : case 4 : document.write("No that's wrong!"); break; case 3 : document.write("Well done!"); } } </script> In fact, I have put in two functions. The second one is activated when the "Done" button is clicked. It examines the value of the variable myAttempt and displays the appropriate message. You will note that the values 1, 2 and 4 all trigger the same clause of the switch statement. In fact, the function guess() only has one statement in it. It might have been more efficient if we had written the statements as follows: <input type="radio" id="q" name="q" onclick="myAttempt=1;"></input> England <BR> <input type="radio" id="q" name="q" onclick="myAttempt=2;"></input> Russia <BR> <input type="radio" id="q" name="q" onclick="myAttempt=3;"></input> China <BR> <input type="radio" id="q" name="q" onclick="myAttempt=4;"></input> Australia In this case, we wouldn't need the function guess() at all! Text areasA text area is similar to a text box, except that it is a large rectangular area on the screen into which the user can type as much text as required. When a text area is defined using the <textarea> tag, you should specify the number of vertical columns and horizontal text rows it should have: <textarea name="typed" cols="30" rows="10"> Any text that you include in here will appear inside the text area. Most programmers leave this part blank! Of course, the user can change the text in here, otherwise there would be no point! </textarea> As you can see, this is one of the few input controls which isn't defined using the <input> tag. The text typed by the user into the text area is obtained using the value property, exactly what we would expect: var masterpiece = myForm.typed.value; or, better still, var masterpiece = document.getElementById("typed").value;. (In this case, myForm is the name of the form in which the text area was enclosed - unnecessary if you use document.getElementById("typed").value). Adding onclick= handlers to other objectsThere is no reason why you shouldn't add event handlers to other objects: <img src="cat.gif" alt="Cat" align="right" onclick="miaou();" /> This will call the function miaou() when the image is clicked on. If you want to add an event handler to a hyperlink reference (a <a href=...> tag) then you should take an extra precaution. You should make the code within the quotation marks a function call which returns the value 0 or false as follows: <a href="" onclick="return myFunc();"> Click on me! </a> Note that the hyperlink reference is left blank here. The function definition should be: function myFunc () { // Normal statements in function here return 0; } The reason for this is that the hyperlink needs to know whether to follow the link or not. If you just included the link as follows ... <a href="" onclick="myFunc();"> Click on me! </a> ... then JavaScript would execute the function, and the web page would try to follow the hyperlink destination. In this case, the hyperlink has been set to an empty string - which confuses the browser no end! (In the case of my browser, it simply shuts down and you find yourself looking at the desktop!) Of course, you may actually want the browser to follow the link after it has carried out the function, in which case, your function needn't return a value, or it could return the value true or 1: <a href="mainmenu.html" onclick="return fadeout();"> Main menu page </a> function fadeout () { var count; for (count = 255; count >= 0; count--) document.bgColor = count; return true; // Could be return 1; } In this case, clicking on the function causes the background to fade from bright blue to black, and then the page changes to the main menu page. Hyperlinks and codeActually, there is an easier way to add code to a hyperlink to a code. You can specify the destination link as a JavaScript function call preceded by javascript: as shown in the following example: <a href="javascript:processNumbers();"> Process the data </a> There is now no need for the return false or the return statement in the hyperlink itself. |