jQuery and Forms - PowerPoint PPT Presentation

About This Presentation
Title:

jQuery and Forms

Description:

jQuery and Forms Part I Learning Objectives By the end of this lecture, you should be able to: Retrieve the values entered by a user into a form using jQuery ... – PowerPoint PPT presentation

Number of Views:92
Avg rating:3.0/5.0
Slides: 13
Provided by: Yosef1
Category:
Tags: forms | hammer | jquery

less

Transcript and Presenter's Notes

Title: jQuery and Forms


1
jQuery and Forms Part I
2
Learning Objectives
  • By the end of this lecture, you should be able
    to
  • Retrieve the values entered by a user into a form
    using jQuery
  • Modify form values using the val() function
  • Know how to use jQuery form selectors
  • Know how to determine which of a group of radio
    buttons was checked using jQuery
  • Determine whether or not a checkbox was checked
    using jQuery
  • Understand when and how to use the ltlabelgt tag

3
Review of JavaScript vs jQueryjQuery and Forms
  • Recall that jQuery is essentially a library of
    JavaScript functions. The developers of jQuery
    analyzed some key / common functionalities of
    JavaScript and have written jQuery methods that
    automate many of them. Some of their goals are to
    reduct the potential for bugs, to shorten the
    amount of code that needs to be written to
    accomplish a given task, and to allow code to
    function among many different browsers in spite
    of inconsistencies among browser behavior.
  • Up to this point, we have spent much of our time
    with jQuery focusing on modifying the styles of a
    web page such as by using the css() and related
    functions, and also modifying the content and
    markup of a page using things like the html() and
    append() functions.
  • However, one of most important (perhaps the most
    important) use of web scripting is having a page
    respond to user input and requests. We do this
    pretty much every day when we we surf the web.
    For example, if you go to a weather website, you
    will at some point notify the page of your
    location or of the location of the geographic
    area you are interested in. At that point, some
    scripting will have to kick in to query a
    database somewhere to retrieve the weather
    information for that particular location.
  • The way that a web site determines the users
    wishes is through form elements such as text
    fields, checkboxes, radio buttons, select
    buttons, and so on. Because form elements are so
    key in scripting, jQuery provides us with all
    kinds of functions to work with them. We will
    spend a little bit of time now learning about
    some of these tools.
  • As always, we will not spend hours and hours
    going through every major function in the jQuery
    API. Rather, the goal is to get you started so
    that if/when you move on, you will know enough
    about how they work to learn how to use
    additional techniques on your own as needed.

4
Selecting / Retrieving / Modifying form elements
  • As you know, the key first step in most jQuery
    commands is selecting something. Well, selecting
    a form element is quite easy in jQuery in fact,
    its quite a bit less wordy than JavaScripts
    getElementById() function. With jQuery we can
    simply use the id attribute of the element and
    invoke the val() function. For example, say you
    have a text field with an id of firstName, as
    shown here
  • ltinput type"text" id"txtFirstName"gt
  • you can easily retrieve the value of this form
    element by typing the following jQuery command
  • var firstName ('txtFirstName').val()
  • Can you also see how you might set the value of a
    form element then? Suppose you have a text field
    into which you intend to write the output of the
    result of some calculation
  • ltinput type"text" id"txtCalculationResult"gt
  • You can use jQuery to enter a value into this
    textfield using the val() function and passing
    that function an argument
  • ('txtCalculationResult').val(36.2247)
  • This would enter the value 36.2247 into the text
    field called txtCalculationResult.

5
Selecting specific form elements by type
  • As you know, the key first step in most jQuery
    commands is selecting something. With forms,
    however, this can be tricky. For example,
    suppose you want to make the background color of
    all of your textfields yellow. You could, in
    theory specify all of them like so
  • ('txtFirstName').css('background-color','yellow
    ')
  • ('txtLastName').css('background-color','yellow'
    )
  • ('txtEmail').css('background-color','yellow')
  • ('txtHomeAddress').css('background-color','yell
    ow')
  • However, I hope you agree that this could quickly
    get tedious!
  • You might be tempted to use
  • ('input').css('background-color','yellow')
  • The problem is that this will color all input
    elements including buttons, checkboxes, and so
    on.
  • Fortunately, jQuery has a series of form
    selectors that allows us to specify specific
    types of form fields. Here is a list from the
    API documentation http//api.jquery.com/category
    /selectors/form-selectors/
  • For example, to select all textfields, you could
    use the text selector.
  • So the complete command would be
  • ('text').css('background-color','yellow')

6
Selecting based on checked
  • One common and very important task in working
    with forms is determining whether or not a
    checkbox has been checked. Another, closely
    related task is to determine which of a group of
    radio buttons was checked.
  • Recall that all radio buttons in a group must
    have the same name. (If the buttons did NOT have
    the same name, the user would be able to choose
    multiple buttons at the same time.)
  • Suppose we ask the user to choose a t-shirt color
    on an ordering page using radio buttons like so
  • Preferred T-Shirt Color?
  • Red ltinput type"radio" name"radColor"
    value"red"gt ltbrgt
  • Blue ltinput type"radio" name"radColor"
    value"blue"gt ltbrgt
  • Green ltinput type"radio" name"radColor"
    value"green"gt ltbrgt
  • You could then determine which button was checked
    by
  • Selecting all input elements
  • Using a filter (remember those? - they are very
    important!!) to only retrieve items with the
    name radColor
  • Applying the checked selector
  • ('inputname"radColor"checked')
  • OTHER NOTES
  • Note that we use double quotes around the value
    of the name attribute. This is to distinguish
    them from the single quotes () around our entire
    jQuery selector.
  • Note our use of the value attribute for a
    series of radio buttons.
  • Also note that we dont have an ID attribute for
    these buttons. Thats fine! If you do not have a
    need to identify any specific form element or
    HTML section, then its perfectly acceptable to
    leave it out.

7
Example Selecting based on checked
  • Preferred T-Shirt Color?
  • Red ltinput type"radio" name"radColor"
    value"red"gt ltbrgt
  • Blue ltinput type"radio" name"radColor"
    value"blue"gt ltbrgt
  • Green ltinput type"radio" name"radColor"
    value"green"gt ltbrgt
  • In a script somewhere,we could have
  • var colorChoice ('inputname"radColor"check
    ed').val()
  • alert("You chose a " colorChoice "
    t-shirt.")
  • Note how we use the val() function to retrieve
    the value of our selection. Do radio buttons have
    to have a value attribute? In many earlier
    examples, our radio buttons did not bother
    including a value attribute, because in those
    cases, they werer not needed. However, in this
    case, it made sense to include this attribute it
    since we want to easily output the color the user
    chose inside our alert statement. In other words,
    deciding which attributes to include (e.g. id
    or value or alt etc, etc) depends on what you
    are planning on doing with that particular HTML
    element.
  • The code seen above is only 2 lines long.
    Hopefully, you can appreciate that this is far
    easier and more elegant then our old way of
    doing it in JavaScript
  • if ( document.formName.radColor0.checked )
  • alert("You chose a " document.formName.radColor
    0.value "t-shirt.")
  • else if ( document.formName.radColor1.checked
    )
  • alert("You chose a " document.formName.radColor
    1.value "t-shirt.")
  • else if ( document.formName.radColor2.checked
    )
  • alert("You chose a " document.formName.radColor
    2.value "t-shirt.")

8
Checking for checked
  • Another common and important task in working with
    forms is to determine if a radio button or
    checkbox has been checked or not. (Do not confuse
    the IF a button was checked with determining
    WHICH of a series of options was checked as
    discussed previously).
  • It would be reasonable to think that we can
    determine if something is checked by using the
    checked selector.
  • For example, suppose you have a pizza ordering
    page with a checkbox for mushrooms called
    chkMushrooms. You might be tempted to ascertain
    if it was checked by typing
  • if ( ('chkMushroomschecked') )
  • alert('You want mushrooms')
  • However this will NOT work for this situation.
    Why? Remember that checked is a selector. In
    other words, it is NOT a function to determine
    whether or not an item has been checked.
  • So how do we check to see if an element was
    checked? Answer Our best bet would be to use
    the prop() function and passing it the argument
    checked like so
  • if ( ('chkMushrooms').prop('checked') )
  • alert('You want mushrooms')
  • ERROR IN BOOK In the 2nd edition of the
    McFarland text, they recommend using the attr()
    function. This method has been deprecated as of
    jQuery version 1.6. So do not use it for this
    particular functionality!

9
Checking for UN-checked
  • What if you are trying to determine if something
    is NOT checked?
  • As you know, the following code will determine if
    something IS checked
  • if ( ('chkMushrooms').prop('checked') )
  • alert('You want mushrooms')
  • However, if you want to determine if something is
    NOT checked, we need to negate our boolean. The
    easiest way to explain this is by an example.
    Again, look at the code to determine if something
    IS checked
  • if ( ('chkMushrooms').prop('checked') )
  • Well, to determine if the opposite is true, we
    use the boolean operator !. The exclamation
    point is basically a big NOT statement. So in
    order to determine if the mushrooms checkbox was
    NOT checked, we put the ! operator before the
    conditional like so
  • if ( !('chkMushrooms').prop('checked') )
  • alert('You do NOT want mushrooms')

10
TRY IT!
  • Open the form_practice.htm and experiment with
    these concepts.
  • Remember that you can mess it up as much as you
    like and simply download a fresh copy from the
    class web page.
  • For example, try writing an if-else statement to
    determine whether or not the user said they were
    good at Hexes. (Feel free to pause the video
    and try it now!)
  • Here is my version
  • if ( ('chkHexes').prop('checked') )
  • alert('You said that you ARE good at hexing')
  • else if ( !('chkHexes').prop('checked') )
  • alert('You said that you are NOT good at
    hexing')

11
The ltlabelgt tag
  • There is one additional tag worth knowing about
    when creating forms. It is called label. Web
    designers sometimes use this tag in the label
    that precedes form elements like so
  • ltlabel for"txtName" id"lblName"gtWhat is your
    name?lt/labelgt
  • ltinput type"text" id"txtName"gt
  • ltlabel for"radPizzaSize" id"labelPizzaSize"gtWhat
    size pizza would you like?lt/labelgt
  • Small ltinput type"radio" name"radPizzaSize"
    id"small"gt
  • Medium ltinput type"radio" name"radPizzaSize"
    id"medium"gt
  • Large ltinput type"radio" name"radPizzaSize"
    id"large"gt
  • The for attribute is optional, although it can
    be helpful. Note that the value assigned to the
    for attribute typically corresponds to the name
    of the form element that the label is intended to
    accompany.
  • However, you will nearly always want to provide
    an id attribute for your labels.
  • The ltlabelgt tag is not necessary, but it can be
    useful. We will make some use of it in an
    upcoming lecture. For example, if the user fails
    to enter a value in a required field (e.g. their
    email address), we will use jQuery to apply some
    kind of highlight to the accompanying label so
    that the user can quickly locate the field that
    they neglected to fill in.

12
Why do we need a ltlabelgt tag?
  • Why bother with the label tag? Why not simply
    use, say, a ltspangt or even ltdivgt tag to surround
    the text that prompts the user? Fair question!
    In fact, in theory we could use ltspangt or ltdivgt
    instead of ltlabelgt.
  • For example, if you wanted, you could just as
    easily wrap the prompt inside a ltspangt tag
  • ltspan id"lblName"gtWhat is your name?lt/spangt
  • ltinput type"text" id"txtName"gt
  • Or, you could even use ltdivgt
  • ltdiv id"lblName"gtWhat is your name?lt/divgt
  • ltinput type"text" id"txtName"gt
  • The reason that any of these would work is
    because all three of these tags ltlabelgt,
    ltspangt, and ltdivgt do not initially DO anything.
    That is, these tags are simply placeholders for
    content. However, remember that just because
    something works does NOT mean that it is the
    right tool for the job. (You could hammer a nail
    with the back of an anvil it would simply be
    the wrong tool for the job!) So how do we decide
    when to use them?
  • ltdivgt tags are used to organize your page into
    sections. When you do that, it not only helps
    with organization, but it also allows us to use
    our scripting tools to work with these sections.
  • ltspangt is mostly used for very small snippets of
    content. For example, we might use this tag as a
    way of applying an inline style to a small bit of
    text or other content.
  • ltlabelgt is typically used to surround some text
    that prompts the user of the kind of information
    they are expected to enter into a form. The
    ltlabelgt tag also supports the for attribute as
    you will have noted in the examples discussed
    previously.
Write a Comment
User Comments (0)
About PowerShow.com