HTML FormsInteracting with the User - PowerPoint PPT Presentation

1 / 56
About This Presentation
Title:

HTML FormsInteracting with the User

Description:

Another form may contain elements that enable the user to ask for a car insurance quote. ... When you insert a new option at a certain index position, beware ... – PowerPoint PPT presentation

Number of Views:67
Avg rating:3.0/5.0
Slides: 57
Provided by: ahad6
Category:

less

Transcript and Presenter's Notes

Title: HTML FormsInteracting with the User


1
HTML Forms-Interacting with the User
2
  • 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 well 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.

3
  • 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 users 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 ltformgt and lt/ formgt
    tags to declare where it starts and where it
    ends.
  • So, to create a blank form, the tags required
    would look something like this

4
  • We access this object in two ways.
  • First, we can access the object directly using
    its namein this case, document.myForm
  • Alternatively, we can access the object through
    the document objects forms array property.
    Remember that in the last chapter we talked about
    the document objects 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 ltformgt 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 ltformgt tag.

5
  • Lets 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.

6
  • 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 well 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.

7
  • 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.

8
  • 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 handlers code
    can affect whether the normal course of events
    continues or is cancelled. We saw, for example,
    that returning false from a hyperlinks onclick
    event handler causes the links navigation to be
    cancelled.
  • Well, the same principle applies to the Form
    objects 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.

9
  • This makes the onsubmit event handlers 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
    users 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.
    Well 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 lets turn our attention to the
    HTML elements that provide interaction
    functionality inside our forms.

10
  • HTML Elements in Forms
  • About ten elements are commonly found within
    ltformgt elements. The most useful are shown in the
    following slides.

11

12

13

14
  • As you can see, most of the form elements are
    created using the ltinputgt tag. One of the ltinputgt
    tags attributes is the type attribute, its 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 elements object
    has its own set of distinctive properties,
    methods, and events. Well 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, lets look at properties and
    methods that the objects of the form elements
    have in common.

15
  • 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 elements 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
    well look at what it means as we look at each
    individual element.

16
  • 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
    pagesthis way you dont need to know the forms
    name in advance.

17
  • Sometimes its useful to know what type of
    element youre dealing with, particularly where
    youre 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 elements 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 buttons onclick event handler code to
    fire, just as if a user had clicked the button
    with his mouse.

18
  • 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 elements objects 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.

19
  • 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
    users 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 elements objects have the onfocus
    and onblur event handlers. These are fired, as
    youd 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.

20
  • 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!

21
  • 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
    users 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.

22
  • Button Form Elements
  • Starting our look at form elements with the
    standard button element because its probably the
    most commonly used and is fairly simple. The HTML
    tag to create a button is the ltinputgt tag. For
    example, to create a button called myButton,
    which has the words Click Me on its face, the
    ltinputgt 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 well 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 youll need to do very often. What
    the button is really all about is the onclick
    event.

23
  • We connect to the buttons onclick event handler
    just as we did for the onclick events of other
    HTML tags such as the ltAgt 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 ltinputgt tag as follows

24
(No Transcript)
25
(No Transcript)
26
  • 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 ltinputgt 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.

27
  • 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 ltinputgt 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 ltinputgt 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 ltinputgt tag would be
    as follows

28
  • 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 users cursor in the right
    place to correct the data and makes it very clear
    to the user where the invalid data is.

29
  • 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 wont do the conversion if the
    operation were 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 ( ) .

30
  • 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
    thats to make a text box read-only. In IF 4.0
    and NN 6 we can use the READONLY attribute of the
    ltinputgt tag or the readonly property of the Text
    object to prevent the contents from being
    changed. However, this wont work on NN 4.x. We
    can get around this using the blur() method.

31
  • All we need to do is add an onfocus event handler
    to the ltinputgt 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 let back up.

32
  • 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 users shoulder and
    discover his or her password. However, when sent
    to the server, the text in the password is sent
    as plain textthere is no encryption or any
    attempt at hiding the textso its 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.

33
  • The Hidden Text Box
  • The hidden text box can hold text and numbers
    just like a normal text box, with the difference
    being that its 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.

34
  • So why are hidden text boxes useful? Lets
    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.

35
  • 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 lttextareagt 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

36
  • The Textarea object created by the lttextareagt tag
    has the same properties, methods, and events as
    the Text object we saw previously except the
    textarea doesnt have the maxlength attribute.
    Note that there is a value property even though
    the lttextareagt tag does not have a value
    attribute. The value property simply returns the
    text between the lttextareagt and lt/ textareagt
    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), lets create an
    example that tells us what events are firing.
  • SEE The example

37
(No Transcript)
38
  • 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.

39
  • Checkboxes and Radio Buttons
  • Creating checkboxes and radio buttons requires
    our old friend the ltinputgt 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 ltinputgt 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 ltinputgt tag will be the following
  • To create a checked radio button, the ltinputgt tag
    would be as follows

40
  • Radio buttons are group elements. in fact, there
    is little point in putting just one on a page
    because the user wont 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

41
  • 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 weve looked at. First, it tells you
    nothing about the users interaction with an
    element, because its predefined in our HTML or
    by our JavaScript.

42
  • 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.

43
  • 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.

44
  • Lets 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

45
  • 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 its out of stock, and the
    4.8-GHz processor speed radio button wont be
    selected. The previous setting will be restored
    once the user dismisses the message box.

46
  • The select Elements
  • Although they look quite different, the drop-down
    list and the list boxes are actually both
    elements created with the ltselectgt 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 ltoptiongt tag.Your
    list of ltoptiongt tags goes in between the
    ltselectgt and lt/selectgt tags.
  • The size attribute of the ltselectgt 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 ltselectgt tag would look like this

47
  • Notice that the Monday ltoptiongt 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 ltselectgt
    tag to 1, and its 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 ltselectgt
    definition.
  • The ltselectgt tag creates a Select object. This
    object has an options array property, and this
    array is made up of Option objects, one for each
    ltoptiongt element inside the ltselectgt element
    associated with the Select object

48
  • For instance, in the preceding example, if the
    ltselectgt 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 objects
    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 whats 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.

49
  • 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. Lets see how we
    could loop through the options array for the
    preceding select box

50
  • 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 ltselectgt tag has been defined.
  • Its also possible to add options to a select
    element after the page has finished loading.
    Well look at how this is done next.

51
  • Adding New Options
  • To add a new option to a select element, we
    simply create a new Option object using the new
    operator and then insert it into the options
    array of the Select object at an empty index
    position.
  • When creating a new Option object, there are two
    parameters to pass
  • the first is the text you want to appear in the
    list, and
  • the second the value to be assigned to the
    option.
  • We then simply assign this Option object to an
    empty array element, for example

52
  • if you want to remove an option, you simply set
    that part of the options array to null. For
    example, to remove the element we just inserted,
    we need the following
  • When you remove an Option object from the options
    array, the array is reordered so that the
    array index values of all the options above the
    removed one have their index value decremented by
    one.
  • When you insert a new option at a certain index
    position, beware that it will overwrite any
    Option object that is already there.

53
  • See The Example
  • The output would be

54
  • Adding New Options with Internet Explorer
  • In IE, many more additional properties, methods,
    and events are associated with objects. in
    particular, the options array we are
    interested in has the additional add () and
    remove () methods, which add and remove options.
    These make life a little simpler.
  • Before we add an option, we need to create it.
    This is done in exactly the same way as before,
    using the new operator.
  • The add () method allows us to insert an Option
    object that we have created and takes two
    parameters. We pass the option that we want to
    add as the first parameter.
  • The optional second parameter allows us to
    specify which index position we want to add the
    option in. This wont overwrite any Option object
    already at that position, but simply moves the
    option objects up the array to make space.

55
  • The remove 0 method takes just one parameter,
    namely the index of the option we want removed.
    When an option is removed, the options at higher
    index positions are moved down the array to fill
    the

56
  • Select Element Events
  • Select elements have three event handlers,
    onblur, on focus, and onchange. Weve seen all
    these events before.
  • We saw the onchange event with the text box
    element, where it fired when focus was moved away
    from the text box and the value in the text box
    had changed. Here it fires when the user changes
    which option in the list is selected.
Write a Comment
User Comments (0)
About PowerShow.com