120 likes | 133 Views
Learn to retrieve, modify, and handle form values using jQuery efficiently. Understand form selectors, checkbox and radio button handling, and the use of <label> tag. Enhance your web scripting skills with jQuery form manipulation techniques.
E N D
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 <label> tag
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 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: <input type="text" id="txtFirstName"> … 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: <input type="text" id="txtCalculationResult"> 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’.
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','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: 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');
Selecting based on ‘checked’ One common and very importanttask 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 <input type="radio" name="radColor" value="red"> <br> Blue <input type="radio" name="radColor" value="blue"> <br> Green <input type="radio" name="radColor" value="green"> <br> 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 :checkedselector: $('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 <input type="radio" name="radColor" value="red"> <br> Blue <input type="radio" name="radColor" value="blue"> <br> Green <input type="radio" name="radColor" value="green"> <br> 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: 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!
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 <label> 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: <label for="txtName" id="lblName">What is your name?</label> <input type="text" id="txtName"> <label for="radPizzaSize" id="labelPizzaSize">What size pizza would you like?</label> Small <input type="radio" name="radPizzaSize" id="small"> Medium <input type="radio" name="radPizzaSize" id="medium"> Large <input type="radio" name="radPizzaSize" id="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 <label> 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.
Why do we need a <label> tag? Why bother with the label tag? Why not simply use, say, a <span> or even <div> tag to surround the text that prompts the user? Fair question! In fact, in theory we could use <span> or <div> instead of <label>. For example, if you wanted, you could just as easily wrap the prompt inside a <span> tag: <span id="lblName">What is your name?</span> <input type="text" id="txtName"> Or, you could even use <div> <div id="lblName">What is your name?</div> <input type="text" id="txtName"> The reason that any of these would work is because all three of these tags: <label>, <span>, and <div> 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? • <div> 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. • <span> 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. • <label> 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 <label> tag also supports the ‘for’ attribute as you will have noted in the examples discussed previously.