560 likes | 577 Views
Learn how to interact with users in web pages and obtain information from them using HTML forms and JavaScript. Explore client-side processing and server-side processing with forms.
E N D
Web pages would be very boring if we could not interact with the user or obtain information from the user, such as text, numbers, or dates. Luckily, with JavaScript this is possible. We can use this information within the web page, or it can be posted to the web server where we can manipulate it and store it in a database if we wish. • In this lecture we’ll concentrate on using the information within the web browser, which is called client-side processing. in Chapters 14 and 15, you can learn how to send this information to a web server and store it in a database, which is called server-side processing.
Forms • Forms provide us with a way of grouping together HTML interaction elements with a common purpose. For example, a form may contain elements that enable the input of a user’s data for registering on a website. Another form may contain elements that enable the user to ask for a car insurance quote. • To create a form, we use the <form> and </ form> tags to declare where it starts and where it ends. • So, to create a blank form, the tags required would look something like this:
We access this object in two ways. • First, we can access the object directly using its name—in this case, document.myForm • Alternatively, we can access the object through the document object’s forms [] array property. Remember that in the last chapter we talked about the document object’s images [] array and how we could manipulate it like any other array. The same applies to the forms [] array, except that instead of each element in the array holding an IMG object, it now holds a Form object. • Many of the attributes of the <form> tag can be accessed as properties of the Form object. in particular, the name property of the Form object mirrors the name attribute of the <form> tag.
Let’s have a look at an example that uses the forms array. Here we have a page with three forms on it. Using the forms [] array, we access each Form object in turn and show the value of its name property in a message box.
Other Form Object Properties and Methods • The HTML form controls commonly found in forms, which we will look at in more detail shortly, also have corresponding objects. One way of accessing these is through the elements [] property of the Form object. • This is an array just like the forms [] array property of the document object that we have just seen. The elements [] array contains all the objects corresponding to the HTML interaction elements within the form. • As we’ll see later, this property is very useful for looping through each of the elements in a form. For example, we could loop through each element to check that it contains valid data prior to submitting the form.
Being an array, the elements [] property of the Form object has the length property, which tells us how many elements are in the form. • The Form object also has the length property, which also gives us the number of elements in the form. Which of these you use is up to you since both do the same job, although writing document .myForm. length is shorter, and therefore quicker to type and less lengthy to look at in code, than document . myForm. elements . length.
When we submit data from a form to a server, we normally use the submit button, which we will come to shortly. However, the Form object also has the submit () method, which does nearly the same thing. It differs in that it does not call the onsubmit event handler for the submit event of the Form object. • Recall that in the last chapter we saw how return values passed back from an event handler’s code can affect whether the normal course of events continues or is cancelled. We saw, for example, that returning false from a hyperlink’s onclick event handler causes the link’s navigation to be cancelled. • Well, the same principle applies to the Form object’s onsubmit event handler, which fires when the user submits the form. if we return true to this event handler, the form submission goes ahead; if we return false, the submission is cancelled.
This makes the onsubmit event handler’s code a great place to do form validation; that is, checking that what the user has entered into the form is valid. For example, if we ask for the user’s age and she enters “mind your own business,” we can spot that this is text rather than a valid number and stop her from continuing. We’ll see this in action when we look at server-side scripting in Chapter 16. • In addition to there being a reset button, which we will discuss later in the chapter, the Form object has the reset ( ) method, which clears the form, or restores default values if these exist. • Creating blank forms is not exactly exciting or useful, so now let’s turn our attention to the HTML elements that provide interaction functionality inside our forms.
HTML Elements in Forms • About ten elements are commonly found within <form> elements. The most useful are shown in the following slides.
As you can see, most of the form elements are created using the <input> tag. One of the <input> tag’s attributes is the type attribute, it’s this attribute that decides which of the HTML elements this will be. Examples of values for this attribute include button (to create a button) and text (to create a text box). • Each form element inside the web page is made available to us as an object. As with all the other objects we have seen, each element’s object has its own set of distinctive properties, methods, and events. We’ll be taking a look at each form element in turn and how to use its particular properties, methods, and events, but before we do that, let’s look at properties and methods that the objects of the form elements have in common.
Common Properties and Methods • One property that all the objects of the form elements have in common is the name property. We can use the value of this property to reference that particular element in our script. Also, if we are sending the information in the form to a server, the element’s name property is sent along with any value of the form element, so that the server knows what the value relates to. • Most form element objects also have the value property in common, which returns the value of the element. For example, for a text box, the value property returns the text that the user has entered in the text box. Also, setting the value of the value property allows us to put text inside the text box. However, the use of the value property is specific to each element, so we’ll look at what it means as we look at each individual element.
All form element objects also have the form property, which returns the Form object in which the element is contained. • This can be useful in cases where you have a generic routine that checks the validity of data in a form. • For example, when the user clicks a submit button, we can pass the Form object referenced by the form property to our data checker, which can use it to loop through each element on the form in turn, checking that data in the element is valid. • This is handy if you have more than one form defined on the page or where you have a generic data checker that you cut and paste to different pages—this way you don’t need to know the form’s name in advance.
Sometimes it’s useful to know what type of element you’re dealing with, particularly where you’re looping through the elements in a form using the elements [] array property of the Form object. This information can be retrieved using the type property, which each element’s object has. This property returns the type of the element (for example, button or text). • All form element objects also have the focus () and blur () methods. Focus is a concept you might not have come across yet. if an element is the center of the focus, any key presses made by the user will be passed directly to that element. For example, if a text box has focus, pressing keys will enter values into the text box. Also, if a button has the focus, pressing the Enter key will cause the button’s onclick event handler code to fire, just as if a user had clicked the button with his mouse.
The user can set which element currently has the focus by clicking on it or by using the Tab key to select it. However, we as the programmer can also decide which element has the focus by using the form element’s object’s focus () method. For example, if we have a text box for the user to enter his age and he enters an invalid value, such as a letter rather than a number, we can tell him that his input is invalid and send him back to that text box to correct his mistake.
Blur, which perhaps could be better named “lost focus,” is the opposite of focus. if we want to remove a form element from being the focus of the user’s attention, we can use the blur () method. When used with a form element, the blur () method usually results in the focus shifting to the page containing the form. • In addition to the focus () and blur () methods, all the form element’s objects have the onfocus and onblur event handlers. These are fired, as you’d expect, when an element gets the focus or loses the focus, due to user action or the focus () and blur () methods. The onblur event handler can be a good place to check the validity of data in the element that has just lost the focus. if invalid, you can set the focus back to the element and let the user know why the data he entered is wrong.
One thing to be careful of is using the focus () or blur () methods in the onfocus or onblur event handler code. • There is a danger of an infinite loop occurring. For example, consider two elements, each of whose on focus events passes the focus to the other element. Then, if one element gets the focus, its onfocus event will pass the focus to the second element, whose onfocus event will pass the focus back to the first element, and so on until the only way out is to close the browser down. • This is not likely to please your users!
Also be very wary of using the focus () and blur () methods to put focus back in a problem field if that field or others depend on some of the user’s input. • For example, say we have two text boxes, one in which we want the user to enter her city and the other in which we want her to enter her state. Also say that the input into the state text box is checked to make sure that the specified city is in that state. • If the state does not contain the city, we put the focus back on the state text box so that the user can change the name of the state. However, if the user actually input the wrong city name and the right state name, she may not be able to go back to the city text box to rectify the problem.
Button Form Elements • Starting our look at form elements with the standard button element because it’s probably the most commonly used and is fairly simple. The HTML tag to create a button is the <input> tag. For example, to create a button called myButton, which has the words “Click Me” on its face, the <input> tag would need to be • The type attribute is set to button, and the value attribute is set to the text we want to appear on the face of the button. We can leave the value attribute off, but we’ll end up with a blank button, which will leave our users guessing as to its purpose. • This element creates an associated Button object; in this example it is called myButton. This object has all the common properties and methods described earlier, including the value property. This allows you to change the text on the button face using JavaScript, though this is probably not something you’ll need to do very often. What the button is really all about is the onclick event.
We connect to the button’s onclick event handler just as we did for the onclick events of other HTML tags such as the <A> tag. All we need do is to define a function that we want to execute when the button is clicked (say, button_onclick ( )) and then add the onclick event handler as an attribute of the <input> tag as follows:
The Submit and Reset Buttons • Two additional types of button are the submit and reset buttons. Defining the submit and reset buttons is done in the same way as defining a standard button, except that the type attribute of the <input> tag is set to submit or reset rather than button. For example • These buttons have special purposes, which are not related to script. When the submit button is clicked, the form data from the form that the button is inside gets automatically sent to the server, without the need for any script. • When the reset button is clicked, all the elements in a form are cleared and returned to their default values; the values they had when the page was first loaded. • The submit and reset buttons have corresponding objects called Submit and Reset, which have exactly the same properties, methods, and events as a standard Button object.
Text Elements • The standard text element allows users to enter a single line of text. This information can then be used in JavaScript code or submitted to a server for server-side processing. A text box is created using the <input> tag, much as our button was, but by setting the type attribute to text. • Again, you can choose not to include the value attribute, but if you do include it this value will appear inside the text box when the page is loaded.in the following example, the <input> tag has two additional attributes of size and maxlength. • The size attribute determines how many characters wide the text box is, and maxlength determines the maximum number of characters the user can enter into the box. • Both attributes are optional and use defaults determined by the browser. For example, to create a text box 10 characters wide, with a maximum character length of 15, and initially containing the words ‘Hello World’, our <input> tag would be as follows:
The Text object that this element creates has a value property, which we can use in our scripting to set or read the text contained inside the text box. • In addition to the common properties and methods we discussed earlier, the Text object also has the select () method, which selects or highlights all the text inside the text box. This may be used if the user has entered an invalid value, and we can set the focus to the text box and select the text inside it. • This then puts the user’s cursor in the right place to correct the data and makes it very clear to the user where the invalid data is.
The value property of Text objects always returns a string data type, even if number characters are being entered. • If we use the value as a number, JavaScript normally does a conversion from a string data type to a number data type for us, • However this is not always the case. For example, JavaScript won’t do the conversion if the operation we’re doing is valid for a string, if we have a form with two text boxes and we added the values returned from these, JavaScript concatenates rather than adds the two values, so 1 + 1 will be 11 and not 2. • To fix this, we need to convert all the values involved to a numerical data type, for example by using parselnt() or parseFloat () or Number ( ) .
in addition to the common event handlers, such as on focus and onblur, the Text object has the onchange, onselect, onkeydown, onkeypress, and onkeyup event handlers. The onselect event fires when the user selects some text in the text box. • More useful is the onchange event, which fires when the element loses focus if (and only if) the value inside the text box is different from the value it had when it got the focus. This enables us to do things like validity checks that occur only if something has changed. • As mentioned before, the onfocus and onblur events can be used for validating user input. However, they also have another purpose, and that’s to make a text box read-only. In IF 4.0+ and NN 6 we can use the READONLY attribute of the <input> tag or the readonly property of the Text object to prevent the contents from being changed. However, this won’t work on NN 4.x. We can get around this using the blur() method.
All we need to do is add an onfocus event handler to the <input> tag defining the text box and connect it to some code that blurs the focus from the text box with the blur method. • The onkeypress, onkeydown, and onkeyup events fire, as their names suggest, when the user presses a key, when the user presses a key down, and when a key pressed down is letback up.
The Password Text Box • The only real purpose of the password box is to allow users to type in a password on a page and to have the password characters hidden, so that no one can look over the user’s shoulder and discover his or her password. However, when sent to the server, the text in the password is sent as plain text—there is no encryption or any attempt at hiding the text—so it’s not a secure way of passing information. • Defining a password box is identical to a text box, except that the type attribute is password. • This form element creates an associated Password object, which is almost identical to the Text object in its properties, methods, and events.
The Hidden Text Box • The hidden text box can hold text and numbers just like a normal text box, with the difference being that it’s not visible to the user. A hidden element? it may sound as useful as an invisible painting, but in fact it proves to be very useful. • To define a hidden text box, we have the following HTML: • The hidden text box creates a Hidden object. This is available in the elements array property of the Form object and can be manipulated in JavaScript like any other object, although we can actually set its value only through its HTML definition or through JavaScript. Like a normal text box, its value is submitted to the server when the user submits the form.
So why are hidden text boxes useful? Let’s imagine we have a lot of information that we need to obtain from the user, but to avoid having a page stuffed full of elements and looking like the control panel of the space shuttle, we decide to obtain the information over more than one page.
textarea Element • The textarea element allows multi-line input of text. Other than this, it acts very much like the text box element. • However, unlike the text box, the textarea element has its own tag, the <textarea> tag. it also has two additional attributes: COLS and ROWS. • The COLS attribute defines how many characters wide the textarea will be, and the ROWS attribute defines how many character rows there will be. Setting the text inside the element is done by putting it between the start and close tags, rather than by using the value attribute. So if we want a textarea element 40 characters wide by 20 rows deep with initial text of “Hello World” on the first line and “Line 2” on the second line, we would define this as follows:
The Textarea object created by the <textarea> tag has the same properties, methods, and events as the Text object we saw previously except the textarea doesn’t have the maxlength attribute. Note that there is a value property even though the <textarea> tag does not have a value attribute. The value property simply returns the text between the <textarea> and </ textarea> tags. The events supported by the Textarea object include the onkeydown, onkeypress, onkeyup, and onchange event handlers. • To help demonstrate how the keydown, keypress, keyup, and change events work (in particular, the order in which they fire), let’s create an example that tells us what events are firing. • SEE The example
Experiment with the example to see what events fire and when. Sometimes you will not get quite the results you expect. For example, if you press and hold a key down, onkeydown and onkeypress will fire in IE and NN 6 and 7 continuously until you let go, when just one onkeyup event will fire.
Checkboxes and Radio Buttons • Creating checkboxes and radio buttons requires our old friend the <input> tag. its type attribute is set to checkbox” or radio to determine which box or button is created. To set a checkbox or a radio button to be checked when the page is loaded, we simply insert the keyword checked into the <input> tag. This is handy if we want to set a default option like, for example, those “Check this box if you want our junk mail” forms you often see on the Net, which are usually checked by default, forcing us to uncheck them. So to create a checkbox that is already checked, our <input> tag will be the following: • To create a checked radio button, the <input> tag would be as follows:
Radio buttons are group elements. in fact, there is little point in putting just one on a page because the user won’t be able to choose between any alternative boxes. • To create a group of radio buttons, we simply give each radio button the same name. This creates an array of radio buttons going by that name that we can access, as we would with any array, using its index. • For example, to create a group of three radio buttons, our HTML would be
We can have as many groups of radio buttons in a form as we want, by just giving each group its own unique name. • Note that we have only used one CHECKED attribute, since only one of the radio buttons in the group can be checked. if we had used the CHECKED attribute in more than one of the radio buttons, only the last of these would have actually been checked. • Using the value attribute of the checkbox and radio button elements is different from previous elements we’ve looked at. First, it tells you nothing about the user’s interaction with an element, because it’s predefined in our HTML or by our JavaScript.
Each checkbox has an associated Checkbox object, and each radio button in a group has a separate Radio object. As mentioned earlier, with radio buttons of the same name, we can access each Radio object in a group by treating the group of radio buttons as an array, with the name of the array being the name of the radio buttons in the group. • As with any array, we have the length property, which will tell us how many radio buttons there are in that group. • For determining whether a user has actually checked or unchecked a checkbox, we need to use the checked property of the Checkbox object. This property returns true if the checkbox is currently checked and false if not.
Radio buttons are slightly different. Because radio buttons with the same name are grouped together, we need to test each Radio object in the group in turn to see if it has been checked. Only one of the radio buttons in a group can be checked, so if you check another one in the group, the previously checked one will become unchecked, and the new one will be checked in its place. • Both checkbox and Radio have the event handlers onclick, onfocus, and onblur, and these operate as we saw for the other elements, although in addition they can also be used to cancel the default action, such as clicking the checkbox or radio button.
Let’s look at an example that makes use of all the properties, methods, and events we have just talked about. The example is a simple form that allows a user to build a computer system. Perhaps it could be used in an e-commerce situation for buying computers online with the exact specification determined by the customer. • See Example • The output would be
Check some of the checkboxes, change the processor speed, and click the Check Form button. A message box will appear giving details of which components and what processor speed you selected. For example, if you select a DVD-ROM and a Zip Drive and 6-GHz processor speed, you will see something like that shown in Figure 6-8. • Note that the 4.8-GHz processor is out of stock, so if you choose that, a message box will appear telling you that it’s out of stock, and the 4.8-GHz processor speed radio button won’t be selected. The previous setting will be restored once the user dismisses themessage box.
The select Elements • Although they look quite different, the drop-down list and the list boxes are actually both elements created with the <select> tag, and strictly speaking they are both select elements. The select element has one or more options in a list that you can select from; each of these options is defined using the <option> tag.Your list of <option> tags goes in between the <select> and </select> tags. • The size attribute of the <select> tag is used to specify how many of the options are visible to the user. For example, to create a list box that is five rows deep and populate it with seven options, our <select> tag would look like this:
Notice that the Monday <option> tag also contains the word selected; this will make this option the default selected one when the page is loaded. The values of the options have been defined as numbers, but text would be equally valid. • If we want this to be a drop-down list, we just need to change the size attribute in the <select> tag to 1, and it’s a drop-down list. • If we want to let the user choose more than one item from a list at once, we simply need to add the multiple attribute to the <select> definition. • The <select> tag creates a Select object. This object has an options [] array property, and this array is made up of Option objects, one for each <option> element inside the <select> element associated with the Select object
For instance, in the preceding example, if the <select> element was contained in a form called theForm, with the following: • we would access the option created for Monday. How can we tell which option has been selected by the user? Easy: we use the Select object’s selected, index property. We can use the index value returned by this property to access the selected option using the options [] array • The Option object also has index, text, and value properties. The index property returns the index position of that option in the options [] array. The text property is what’s displayed in the list, and the value property is the value defined for the option, which would be posted to the server if the form were submitted.
If you want to find out how many options there are in a select element, you can use the length property of either the Select object itself or of its options [] array property. Let’s see how we could loop through the options [] array for the preceding select box:
First we set the variable theDayElement to reference the Select object. Then we write the number of options to the page, in this case 7. • Next we use a for loop to loop through the options [] array, displaying the text of each option, such as Monday, Tuesday, and so on, and its value, such as 0, 1, and so on. if you create a page based on this code, it must be placed after the <select> tag has been defined. • It’s also possible to add options to a select element after the page has finished loading. We’ll look at how this is done next.