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.

Slides:



Advertisements
Similar presentations
23-Aug-14 HTML/XHTML Forms. 2 What are forms? is just another kind of XHTML/HTML tag Forms are used to create (rather primitive) GUIs on Web pages Usually.
Advertisements

Introduction to HTML & CSS
HTML – A Brief introduction Title of page This is my first homepage. This text is bold  The first tag in your HTML document is. This tag tells your browser.
Introduction to CSS.
Modifying existing content Adding/Removing content on a page using jQuery.
Events Part III The event object. Learning Objectives By the end of this lecture, you should be able to: – Learn to use the hover() function – Work with.
CSS cont. October 5, Unit 4. Padding We can add borders around the elements of our pages To increase the space between the content and the border, use.
“Cascading Style Sheets” for styling WWW information DSC340 Mike Pangburn.
Form Validation. Learning Objectives By the end of this lecture, you should be able to: – Describe what is meant by ‘form validation’ – Understand why.
CHAPTER 30 THE HTML 5 FORMS PROCESSING. LEARNING OBJECTIVES What the three form elements are How to use the HTML 5 tag to specify a list of words’ form.
Escaping Characters document.write(). Learning Objectives By the end of this lecture, you should be able to: – Recognize some of the characters that can.
There is a certain way that an HTML file should be set up. The HTML section declares a beginning and an ending. Within the HTML, there should be a HEAD.
Creating Web Page Forms
1 Using jQuery JavaScript & jQuery the missing manual (Second Edition)
Random Stuff Colors Sizes CSS Shortcuts. Learning Objectives By the end of this lecture, you should be able to: – Identify the 3 most common ways in which.
Working with Numbers parseInt() and parseFloat() Math.round() Other Math object functions isNaN() toFixed()
Reading Data in Web Pages tMyn1 Reading Data in Web Pages A very common application of PHP is to have an HTML form gather information from a website's.
CO1552 Web Application Development HTML Forms. Websites can be made more interactive by providing facilities for users to provide data To get user entered.
JavaScript & jQuery the missing manual Chapter 11
DAT602 Database Application Development Lecture 14 HTML.
Selectors. Learning Objectives By the end of this lecture, you should be able to: – Select items using jQuery based on ID, class name, or HTML tag. –
1 Direct Manipulation Proposal 17 Direct Manipulation is when physical actions are used instead of commands. E.g. In a word document when the user inputs.
225 City Avenue, Suite 106 Bala Cynwyd, PA , phone , fax presents… HTML Lists, Tables and Forms v2.0.
Using the API. Learning Objectives By the end of this lecture, you should be able to: – Identify what is meant by an ‘API’ – Know how to look up functions.
Fluency with Information Technology INFO100 and CSE100 Katherine Deibel Katherine Deibel, Fluency in Information Technology1.
1 Essential HTML coding By Fadi Safieddine (Week 2)
Review IDIA 619 Spring 2013 Bridget M. Blodgett. HTML A basic HTML document looks like this: Sample page Sample page This is a simple sample. HTML user.
INTRODUCTION TO HTML5 Using jQuery with HTML5. Introducing jQuery  Although it is not a part of any W3C or WHATWG specification, jQuery performs an important.
Extending HTML CPSC 120 Principles of Computer Science April 9, 2012.
IS1825: Developing Multimedia Applications for Business Lecture 1: Introduction to CSS Rob Gleasure
 Whether using paper forms or forms on the web, forms are used for gathering information. User enter information into designated areas, or fields. Forms.
Animation & Effects Using JQuery. What is jQuery? jQuery is a lightweight, JavaScript library. The purpose of jQuery is to make it much easier to use.
Events Part II Browser Variations Document / Window Events Form Events --- Using named functions (instead of anonymous)
Working with Files. Learning Objectives By the end of this lecture, you should be able to: – Examine a file that contains code with unfamiliar material,
Return values Efficiency in Coding. Learning Objectives By the end of this lecture, you should be able to: – Be able to apply an ‘object literal’ when.
CSD 340 (Blum)1 Starting JavaScript Homage to the Homage to the Square.
HTML Forms. Slide 2 Forms (Introduction) The purpose of input forms Organizing forms with a and Using different element types to get user input A brief.
Sahar Mosleh California State University San MarcosPage 1 JavaScript Basic.
JQuery JavaScript is a powerful language but it is not always easy to work with. jQuery is a JavaScript library that helps with: – HTML document traversal.
Modifying HTML attributes and CSS values. Learning Objectives By the end of this lecture, you should be able to: – Select based on a class (as opposed.
Working with Strings. Learning Objectives By the end of this lecture, you should be able to: – Appreciate the need to search for and extract information.
CSD 340 (Blum)1 Starting JavaScript Homage to the Homage to the Square.
1 CSC160 Chapter 7: Events and Event Handlers. 2 Outline Event and event handlers onClick event handler onMouseOver event handler onMouseOut event handler.
Student Pages
Events Part I Mouse Events. Learning Objectives By the end of this lecture, you should be able to: – Understand what is meant by an ‘event’ – Appreciate.
Changing HTML Attributes each() function Anonymous Functions $(this) keyword.
Review of HTML and CSS A (very) brief review of some key fundamentals to be aware of in IT-238.
Department of Computer Science, Florida State University CGS 3066: Web Programming and Design Spring Forms, HTML5 layout.
HTML Tutorial. What is HTML HTML is a markup language for describing web documents (web pages) HTML documents are described by HTML tags Each HTML tag.
1 Using jQuery JavaScript & jQuery the missing manual (Second Edition)
Lesson 5 Introduction to HTML Forms. Lesson 5 Forms A form is an area that can contain form elements. Form elements are elements that allow the user to.
Loops Brent M. Dingle Texas A&M University Chapter 6 – Section 6.3 Multiway Branches (and some from Mastering Turbo Pascal 5.5, 3 rd Edition by Tom Swan)
JavaScript – If/Else contd
JavaScript Controlling the flow of your programs with ‘if’ statements
Moving away from alert() Using innerHTML Using an empty div section
Checkboxes, Select boxes, Radio buttons,
Retrieving information from forms
HTML Forms and User Input
Conditions and Ifs BIS1523 – Lecture 8.
Removing events Stopping an event’s normal behavior
Working with ‘checked’ items Checkboxes and Radio buttons
Events Part I Mouse Events.
Selectors.
Events Part III The event object.
Modifying HTML attributes and CSS values
Random Stuff Colors Sizes CSS Shortcuts.
Using the API.
Retrieving information from forms
Checkboxes, Select boxes, Radio buttons
Adios alert() Using innerHTML Using an empty section
Presentation transcript:

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 – 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 tag

Review of JavaScript vs jQuery jQuery 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 user’s 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.

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, it’s quite a bit less wordy than JavaScript’s 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: … 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: You can use jQuery to enter a value into this textfield using the val() function and passing that function an argument: $('#txtCalculationResult').val( ); This would enter the value into the text field called ‘ txtCalculationResult ’.

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'); $('#txt ').css('background-color','yellow'); $('#txtHomeAddress').css('background-color','yellow'); 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: For example, to select all textfields, you could use the :text selector. So the complete command would be: $(':text').css('background-color','yellow');

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 Blue Green You could then determine which button was checked by 1.Selecting all ‘input’ elements 2.Using a filter (remember those? - they are very important!!) to only retrieve items with the name ‘ radColor ’ 3.Applying the : checked selector: $('input[name="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 don’t have an ID attribute for these buttons. That’s fine! If you do not have a need to identify any specific form element or HTML section, then it’s perfectly acceptable to leave it out. The next slide puts this all together in an example.

Example: Selecting based on ‘checked’ Preferred T-Shirt Color? Red Blue Green In a script somewhere,we could have: var colorChoice = $('input[name="radColor"]:checked').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.radColor[0].checked ) alert("You chose a " + document.formName.radColor[0].value + "t-shirt."); else if ( document.formName.radColor[1].checked ) alert("You chose a " + document.formName.radColor[1].value + "t-shirt."); else if ( document.formName.radColor[2].checked ) alert("You chose a " + document.formName.radColor[2].value + "t-shirt.");

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 ( $('#chkMushrooms:checked') ) 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: prop() function if ( $('#chkMushrooms').prop('checked') ) alert('You want mushrooms'); ERROR IN BOOK: In the 2 nd 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!

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');

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');

The 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: What is your name? What size pizza would you like? Small Medium Large 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 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 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.

Why do we need a tag? Why bother with the label tag? Why not simply use, say, a or even tag to surround the text that prompts the user? Fair question! In fact, in theory we could use or instead of. For example, if you wanted, you could just as easily wrap the prompt inside a tag: What is your name? Or, you could even use What is your name? The reason that any of these would work is because all three of these tags:,, and 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? 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. 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. 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 tag also supports the ‘ for ’ attribute as you will have noted in the examples discussed previously.