Beginning JavaScript Third Edition phần 4 pdf

79 608 0
Beginning JavaScript Third Edition phần 4 pdf

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

An alternative way of finding out which radio button was clicked would be to loop through the radio button group’s array and test each radio button in turn to see if it was checked. The code would look something like this: var radIndex; for (radIndex = 0; radIndex < document.form1.radCPUSpeed.length; radIndex++) { if (document.form1.radCPUSpeed[radIndex].checked == true) { radCpuSpeedIndex = radIndex; break; } } But to get back to the actual code, you’ll notice a few new-line (\n) characters thrown into the message string for formatting reasons. Next you have your big for statement. for (controlIndex = 0; controlIndex < numberOfControls; controlIndex++) { element = document.form1[controlIndex]; if (element.type == “checkbox”) { if (element.checked == true) { compSpec = compSpec + element.value + “\n”; } } } alert(compSpec); } It’s here that you loop through each element on the form using document.form1[controlIndex], which returns a reference to the element object stored at the controlIndex index position. You’ll see that in this example the element variable is set to reference the object stored in the form1[] array at the index position stored in variable controlIndex. Again, this is for convenient shorthand purposes; now to use that particular object’s properties or methods, you just type element, a period, and then the method or property name, making your code easier to read and debug, which also saves on typing. You only want to see which check boxes have been checked, so you use the type property, which every HTML element object has, to see what element type you are dealing with. If the type is checkbox, you go ahead and see if it’s a checked check box. If so, you append its value to the message string in compSpec. If it is not a check box, it can be safely ignored. Finally, you use the alert() method to display the contents of your message string. 214 Chapter 6: HTML Forms — Interacting with the User 09_051511 ch06.qxp 4/13/07 6:20 PM Page 214 The select Elements Although they look quite different, the drop-down list and the list boxes are actually both elements cre- ated 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 by means of 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 five rows deep and populate it with seven options, your <select> tag would look like this: <select name=theDay size=5> <option value=0 selected>Monday <option value=1>Tuesday <option value=2>Wednesday <option value=3>Thursday <option value=4>Friday <option value=5>Saturday <option value=6>Sunday </select> 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 you want this to be a drop-down list, you just need to change the size attribute in the <select> tag to 1, and presto, it’s a drop-down list. If you want to let the user choose more than one item from a list at once, you 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: document.theForm.theDay.options[0] you would access the option created for Monday. How can you tell which option has been selected by the user? Easy: You use the Select object’s selectedIndex property. You 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. 215 Chapter 6: HTML Forms — Interacting with the User 09_051511 ch06.qxp 4/13/07 6:20 PM Page 215 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 you could loop through the options[] array for the preceding select box: var theDayElement = window.document.form1.theDay; document.write(“There are “ + theDayElement.length + “options<br>”); var optionCounter; for (optionCounter = 0; optionCounter < theDayElement.length; optionCounter++) { document.write(“Option text is “ + theDayElement.options[optionCounter].text) document.write(“ and its value is “); document.write(theDayElement.options[optionCounter].value); document.write(“<br>”) } First you set the variable theDayElement to reference the Select object. Then you write the number of options to the page, in this case 7. Next you 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. You’ll look at how this is done next. Adding New Options To add a new option to a select element, you 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 you create 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. var myNewOption = new Option(“TheText”,”TheValue”); You then simply assign this Option object to an empty array element, for example: document.theForm.theSelectObject.options[0] = myNewOption; If you want to remove an option, you simply set that part of the options[] array to null. For example, to remove the element you just inserted, you need the following: document.theForm.theSelectObject.options[0] = null; When you remove an Option object from the options[] array, the array is reordered so that the array index value of each of the options above the removed one has its index value decremented by one. When you insert a new option at a certain index position, be aware that it will overwrite any Option object that is already there. 216 Chapter 6: HTML Forms — Interacting with the User 09_051511 ch06.qxp 4/13/07 6:20 PM Page 216 Try It Out Adding and Removing List Options Use the list-of-days example you saw previously to demonstrate adding and removing list options. <html> <head> <script language=”JavaScript” type=”text/javascript”> function butRemoveWed_onclick() { if (document.form1.theDay.options[2].text == “Wednesday”) { document.form1.theDay.options[2] = null; } else { alert(‘There is no Wednesday here!’); } } function butAddWed_onclick() { if (document.form1.theDay.options[2].text != “Wednesday”) { var indexCounter; var days = document.form1.theDay; var lastoption = new Option(); days.options[6] = lastoption; for (indexCounter = 6;indexCounter > 2; indexCounter ) { days.options[indexCounter].text = days.options[indexCounter - 1].text; days.options[indexCounter].value = days.options[indexCounter - 1].value; } var option = new Option(“Wednesday”,2); days.options[2] = option; } else { alert(‘Do you want to have TWO Wednesdays?????’); } } </script> </head> <body> <form name=form1> <select name=theDay size=5> <option value=0 selected>Monday <option value=1>Tuesday <option value=2>Wednesday <option value=3>Thursday <option value=4>Friday <option value=5>Saturday <option value=6>Sunday </select> <BR> <input type=”button” value=”Remove Wednesday” name=butRemoveWed 217 Chapter 6: HTML Forms — Interacting with the User 09_051511 ch06.qxp 4/13/07 6:20 PM Page 217 onclick=”butRemoveWed_onclick()”> <input type=”button” value=”Add Wednesday” name=butAddWed onclick=”butAddWed_onclick()”> <BR> </form> </body> </html> Save this as ch6_examp7.htm. If you type the page in and load it into your browser, you should see the form shown in Figure 6-9. Click the Remove Wednesday button, and you’ll see Wednesday disappear from the list. Add it back by clicking the Add Wednesday button. If you try to add a second Wednesday or remove a nonexistent Wednesday, you’ll get a polite warning telling you that you can’t do that. Figure 6-9 How It Works Within the body of the page, you define a form with the name form1. This contains the select element, which includes day-of-the-week options that you have seen previously. The form also contains two but- tons, as shown here: <input type=”button” value=”Remove Wednesday” name=butRemoveWed onclick=”butRemoveWed_onclick()”> <input type=”button” value=”Add Wednesday” name=butAddWed onclick=”butAddWed_onclick()”> Each of these buttons has its onclick event handler connected to some code that calls one of two func- tions: butRemoveWed_onclick() and butAddWed_onclick(). These functions are defined in a script block in the head of the page. You’ll take a look at each of them in turn. 218 Chapter 6: HTML Forms — Interacting with the User 09_051511 ch06.qxp 4/13/07 6:20 PM Page 218 At the top of the page you have your first function, butRemoveWed_onclick(), which removes the Wednesday option. function butRemoveWed_onclick() { if (document.form1.theDay.options[2].text == “Wednesday”) { document.form1.theDay.options[2] = null; } else { alert(‘There is no Wednesday here!’); } } The first thing you do in the function is a sanity check: You must try to remove the Wednesday option only if it’s there in the first place! You make sure of this by seeing if the third option in the array (with index 2 because arrays start at index 0) has the text “Wednesday”. If it does, you can remove the Wednesday option by setting that particular option to null. If the third option in the array is not Wednesday, you alert the user to the fact that there is no Wednesday to remove. Although this code uses the text property in the if statement’s condition, you could just as easily have used the value prop- erty; it makes no difference. Next you come to the butAddWed_onclick() function, which, as the name suggests, adds the Wednesday option. This is slightly more complex than the code required to remove an option. First you use an if statement to check that there is not already a Wednesday option. function butAddWed_onclick() { if (document.form1.theDay.options[2].text != “Wednesday”) { var indexCounter; var days = document.form1.theDay; var lastoption = new Option(); days.options[6] = lastoption; for (indexCounter = 6;indexCounter > 2; indexCounter ) { days.options[indexCounter].text = days.options[indexCounter - 1].text; days.options[indexCounter].value = days.options[indexCounter - 1].value; } If there is no Wednesday option, you then need to make space for the new Wednesday option to be inserted. Before you do this, you define two variables, indexCounter and days (which refers to theDay select element and is a shorthand reference for your convenience). Next you create a new option with the vari- able name lastoption and assign this new option to the element at index position 6 in your options array, which previously had no contents. You next assign the text and value properties of each of the Option objects from Thursday to Sunday to the Option at an index value higher by one in the options array, leaving a space in the options array at position 2 to put Wednesday in. This is the task for the for loop within the if statement. 219 Chapter 6: HTML Forms — Interacting with the User 09_051511 ch06.qxp 4/13/07 6:20 PM Page 219 Next, you create a new Option object by passing the text “Wednesday” and the value 2 to the Option constructor. The Option object is then inserted into the options[] array at position 2, and presto, it appears in your select box. var option = new Option(“Wednesday”,2); days.options[2] = option; } You end the function by alerting the user to the fact that there is already a Wednesday option in the list, if the condition in the if statement is false. else { alert(‘Do you want to have TWO Wednesdays?????’); } } Adding New Options with Internet Explorer In IE, additional properties, methods, and events are associated with the select options. In particular, the options[] array you are interested in has the additional add() and remove() methods, which add and remove options. These make life a little simpler. Before you add an option, you need to create it. You do this just as before, using the new operator. The add() method enables you to insert an Option object that you have created and takes two parame- ters. You pass the option that you want to add as the first parameter. The optional second parameter enables you to specify which index position you want to add the option in. This parameter won’t over- write any Option object already at that position, but instead will simply move the Option objects up the array to make space. This is basically the same as what you had to code into the butAddWed_onclick() function using your for loop. Using the add() method, you can rewrite the butAddWed_onclick() function in your ch6_examp7.htm example to look like this: function butAddWed_onclick() { if (document.form1.theDay.options[2].text != “Wednesday”) { var option = new Option(“Wednesday”,2); document.form1.theDay.options.add(option,2); } else { alert(‘Do you want to have TWO Wednesdays?????’); } } The remove() method takes just one parameter, namely the index of the option you want removed. When an option is removed, the options at higher index positions are moved down the array to fill the gap. 220 Chapter 6: HTML Forms — Interacting with the User 09_051511 ch06.qxp 4/13/07 6:20 PM Page 220 Using the remove() method, you can rewrite the butRemoveWed_onclick() function in your ch6_examp7.htm example to look like this: function butRemoveWed_onclick() { if (document.form1.theDay.options[2].text == “Wednesday”) { document.form1.theDay.options.remove(2); } else { alert(‘There is no Wednesday here!’); } } Modify the previous example and save it as ch6_examp8_IE.htm before loading it into IE. You’ll see that it works just as the previous version did. Select Element Events Select elements have three event handlers, onblur, onfocus, and onchange. You’ve seen all these events before. You 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. Try It Out Using the Select Element for Date Difference Calculations Let’s take a look at an example that uses the onchange event and makes good use of the select element in its drop-down list form. Its purpose is to calculate the difference, in days, between two dates set by the user via drop-down list boxes. <html> <head> <script language=”JavaScript” type=”text/javascript”> function writeOptions(startNumber, endNumber) { var optionCounter; for (optionCounter = startNumber; optionCounter <= endNumber; optionCounter++) { document.write(‘<option value=’ + optionCounter + ‘>’ + optionCounter); } } function writeMonthOptions() { var theMonth; var monthCounter; var theDate = new Date(1); for (monthCounter = 0; monthCounter < 12; monthCounter++) { theDate.setMonth(monthCounter); theMonth = theDate.toString(); theMonth = theMonth.substr(4,3); document.write(‘<option value=’ + theMonth + ‘>’ + theMonth); 221 Chapter 6: HTML Forms — Interacting with the User 09_051511 ch06.qxp 4/13/07 6:20 PM Page 221 } } function recalcDateDiff() { var myForm = document.form1; var firstDay = myForm.firstDay.options[myForm.firstDay.selectedIndex].value; var secondDay = myForm.secondDay.options[myForm.secondDay.selectedIndex].value; var firstMonth = myForm.firstMonth.options[myForm.firstMonth.selectedIndex].value; var secondMonth = myForm.secondMonth.options[myForm.secondMonth.selectedIndex].value; var firstYear = myForm.firstYear.options[myForm.firstYear.selectedIndex].value; var secondYear = myForm.secondYear.options[myForm.secondYear.selectedIndex].value; var firstDate = new Date(firstDay + “ “ + firstMonth + “ “ + firstYear); var secondDate = new Date(secondDay + “ “ + secondMonth + “ “ + secondYear); var daysDiff = (secondDate.valueOf() - firstDate.valueOf()); daysDiff = Math.floor(Math.abs((((daysDiff / 1000) / 60) / 60) / 24)); myForm.txtDays.value = daysDiff; return true; } function window_onload() { var theForm = document.form1; var nowDate = new Date(); theForm.firstDay.options[nowDate.getDate() - 1].selected = true; theForm.secondDay.options[nowDate.getDate() - 1].selected = true; theForm.firstMonth.options[nowDate.getMonth()].selected = true; theForm.secondMonth.options[nowDate.getMonth()].selected = true; theForm.firstYear.options[nowDate.getFullYear()- 1970].selected = true; theForm.secondYear.options[nowDate.getFullYear() - 1970].selected = true; } </script> </head> <body language=JavaScript onload=”return window_onload()”> <form name=form1> <p> First Date<br> <select name=firstDay size=1 onchange=”return recalcDateDiff()”> <script language=JavaScript> writeOptions(1,31); </script> </select> <select name=firstMonth size=1 onchange=”return recalcDateDiff()”> <script language=JavaScript> writeMonthOptions(); </script> </select> <select name=firstYear size=1 onchange=”return recalcDateDiff()”> <script language=JavaScript> writeOptions(1970,2020); </script> </select> 222 Chapter 6: HTML Forms — Interacting with the User 09_051511 ch06.qxp 4/13/07 6:20 PM Page 222 </p> <p> Second Date<br> <select name=secondDay size=1 onchange=”return recalcDateDiff()”> <script language=JavaScript> writeOptions(1,31); </script> </select> <select name=secondMonth size=1 onchange=”return recalcDateDiff()”> <script language=JavaScript> writeMonthOptions(); </script> </select> <select name=secondYear size=1 onchange=”return recalcDateDiff()”> <script language=JavaScript> writeOptions(1970,2020); </script> </select> </p> Total difference in days <input type=”text” name=txtDays value=0 readonly> <br> </form> </body> </html> Call the example ch6_examp9.htm and load it into your web browser. You should see the form shown in Figure 6-10, but with both date boxes set to the current date. Figure 6-10 223 Chapter 6: HTML Forms — Interacting with the User 09_051511 ch06.qxp 4/13/07 6:20 PM Page 223 [...]... for example, Sat Feb 19 19: 04: 34 2000 You just need the month part Since you always know where it will be in the string and that its length is always 3, you can easily use the String object’s substr() method to extract the month for (monthCounter = 0; monthCounter < 12; monthCounter++) { theDate.setMonth(monthCounter); theMonth = theDate.toString(); theMonth = theMonth.substr (4, 3); document.write(‘ . recalcDateDiff()”> <script language =JavaScript& gt; writeOptions(1970,2020); </script> </select> 2 24 Chapter 6: HTML Forms — Interacting with the User 09_051511 ch06.qxp 4/ 13/07 6:20 PM Page 2 24 To populate. to display the contents of your message string. 2 14 Chapter 6: HTML Forms — Interacting with the User 09_051511 ch06.qxp 4/ 13/07 6:20 PM Page 2 14 The select Elements Although they look quite different,. name=txtQNumber size=1> <script language= JavaScript type=”text /javascript > 228 Chapter 6: HTML Forms — Interacting with the User 09_051511 ch06.qxp 4/ 13/07 6:20 PM Page 228 document.write(getQuestion()); </script> <input

Ngày đăng: 09/08/2014, 14:21

Mục lục

  • Beginning JavaScript, Third Edition

    • Chapter 6: HTML Forms — Interacting with the User

      • HTML Elements in Forms

        • The select Elements

        • The Trivia Quiz

          • Creating the Form

          • Creating the Answer Radio Buttons

          • Summary

          • Exercises

            • Question 1

            • Question2

            • Chapter 7: Windows and Frames

              • Frames and the window Object

                • Coding Between Frames

                • Code Access Between Frames

                • Opening New Windows

                  • Opening a New Browser Window

                  • Scripting Between Windows

                  • Moving and Resizing Windows

                  • Security

                  • Trivia Quiz

                    • Creating the New Trivia Quiz

                    • Summary

                    • Exercise Questions

                      • Question 1

                      • Question 2

                      • Chapter 8: String Manipulation

                        • Additional String Methods

                          • The split() Method

Tài liệu cùng người dùng

Tài liệu liên quan