1CGI::HTML::Functions(3)User Contributed Perl DocumentatioCnGI::HTML::Functions(3)
2
3
4
6 CGI::HTML::Functions - Documentation for CGI.pm Legacy HTML
7 Functionality
8
10 Nothing here - please do not use this functionality, it is considered
11 to be legacy and essentially deprecated. This documentation exists
12 solely to aid in maintenance and migration of legacy code using this
13 functionality and you are strongly encouraged to migrate away from it.
14 If you are working on new code you should be using a template engine.
15 For more information see CGI::Alternatives.
16
17 If you really want to continue using the HTML generation functionality
18 of CGI.pm then you should take a look at HTML::Tiny instead, which may
19 give you a migration path away from CGI.pm's html generation functions;
20 i strongly encourage you to move towards template driven page
21 generation for anything involving markup as it will make porting your
22 app to other frameworks much easier in the long run.
23
25 The documentation here should be considered an addendum to the sections
26 in the CGI documentation - the sections here are named the same as
27 those within the CGI perldoc.
28
30 HTML tag functions have both attributes (the attribute="value" pairs
31 within the tag itself) and contents (the part between the opening and
32 closing pairs). To distinguish between attributes and contents, CGI.pm
33 uses the convention of passing HTML attributes as a hash reference as
34 the first argument, and the contents, if any, as any subsequent
35 arguments. It works out like this:
36
37 Code Generated HTML
38 ---- --------------
39 h1() <h1 />
40 h1('some','contents'); <h1>some contents</h1>
41 h1({-align=>left}); <h1 align="LEFT">
42 h1({-align=>left},'contents'); <h1 align="LEFT">contents</h1>
43
44 Many newcomers to CGI.pm are puzzled by the difference between the
45 calling conventions for the HTML shortcuts, which require curly braces
46 around the HTML tag attributes, and the calling conventions for other
47 routines, which manage to generate attributes without the curly
48 brackets. Don't be confused. As a convenience the curly braces are
49 optional in all but the HTML shortcuts. If you like, you can use curly
50 braces when calling any routine that takes named arguments. For
51 example:
52
53 print $q->header( { -type => 'image/gif', -expires => '+3d' } );
54
55 If you use warnings, you will be warned that some CGI.pm argument names
56 conflict with built-in perl functions. The most frequent of these is
57 the -values argument, used to create multi-valued menus, radio button
58 clusters and the like. To get around this warning, you have several
59 choices:
60
61 1. Use another name for the argument, if one is available. For
62 example, -value is an alias for -values.
63
64 2. Change the capitalization, e.g. -Values
65
66 3. Put quotes around the argument name, e.g. '-values'
67
68 Function-oriented interface HTML exports
69 Here is a list of the HTML related function sets you can import:
70
71 :form
72 Import all fill-out form generating methods, such as textfield().
73
74 :html2
75 Import all methods that generate HTML 2.0 standard elements.
76
77 :html3
78 Import all methods that generate HTML 3.0 elements (such as
79 <table>, <super> and <sub>).
80
81 :html4
82 Import all methods that generate HTML 4 elements (such as <abbrev>,
83 <acronym> and <thead>).
84
85 :netscape
86 Import the <blink>, <fontsize> and <center> tags.
87
88 :html
89 Import all HTML-generating shortcuts (i.e. 'html2', 'html3',
90 'html4' and 'netscape')
91
92 :standard
93 Import "standard" features, 'html2', 'html3', 'html4', 'ssl',
94 'form' and 'cgi'.
95
96 If you import any of the state-maintaining CGI or form-generating
97 methods, a default CGI object will be created and initialized
98 automatically the first time you use any of the methods that require
99 one to be present. This includes param(), textfield(), submit() and the
100 like. (If you need direct access to the CGI object, you can find it in
101 the global variable $CGI::Q).
102
103 Pragmas
104 Additional HTML generation related pragms:
105
106 -nosticky
107 By default the CGI module implements a state-preserving behavior
108 called "sticky" fields. The way this works is that if you are
109 regenerating a form, the methods that generate the form field
110 values will interrogate param() to see if similarly-named
111 parameters are present in the query string. If they find a like-
112 named parameter, they will use it to set their default values.
113
114 Sometimes this isn't what you want. The -nosticky pragma prevents
115 this behavior. You can also selectively change the sticky behavior
116 in each element that you generate.
117
118 -tabindex
119 Automatically add tab index attributes to each form field. With
120 this option turned off, you can still add tab indexes manually by
121 passing a -tabindex option to each field-generating method.
122
123 -no_xhtml
124 By default, CGI.pm versions 2.69 and higher emit XHTML
125 (http://www.w3.org/TR/xhtml1/). The -no_xhtml pragma disables this
126 feature. Thanks to Michalis Kabrianis <kabrianis@hellug.gr> for
127 this feature.
128
129 If start_html()'s -dtd parameter specifies an HTML 2.0, 3.2, 4.0 or
130 4.01 DTD, XHTML will automatically be disabled without needing to
131 use this pragma.
132
133 Special forms for importing HTML-tag functions
134 Many of the methods generate HTML tags. As described below, tag
135 functions automatically generate both the opening and closing tags. For
136 example:
137
138 print h1('Level 1 Header');
139
140 produces
141
142 <h1>Level 1 Header</h1>
143
144 There will be some times when you want to produce the start and end
145 tags yourself. In this case, you can use the form start_tag_name and
146 end_tag_name, as in:
147
148 print start_h1,'Level 1 Header',end_h1;
149
150 Creating the HTML document header
151 print start_html(
152 -title => 'Secrets of the Pyramids',
153 -author => 'fred@capricorn.org',
154 -base => 'true',
155 -target => '_blank',
156 -meta => {'keywords'=>'pharaoh secret mummy',
157 'copyright' => 'copyright 1996 King Tut'},
158 -style => {'src'=>'/styles/style1.css'},
159 -BGCOLOR => 'blue'
160 );
161
162 The start_html() routine creates the top of the page, along with a lot
163 of optional information that controls the page's appearance and
164 behavior.
165
166 This method returns a canned HTML header and the opening <body> tag.
167 All parameters are optional. In the named parameter form, recognized
168 parameters are -title, -author, -base, -xbase, -dtd, -lang and -target
169 (see below for the explanation). Any additional parameters you provide,
170 such as the unofficial BGCOLOR attribute, are added to the <body> tag.
171 Additional parameters must be proceeded by a hyphen.
172
173 The argument -xbase allows you to provide an HREF for the <base> tag
174 different from the current location, as in
175
176 -xbase => "http://home.mcom.com/"
177
178 All relative links will be interpreted relative to this tag.
179
180 The argument -target allows you to provide a default target frame for
181 all the links and fill-out forms on the page. This is a non-standard
182 HTTP feature which only works with some browsers!
183
184 -target => "answer_window"
185
186 All relative links will be interpreted relative to this tag. You add
187 arbitrary meta information to the header with the -meta argument. This
188 argument expects a reference to a hash containing name/value pairs of
189 meta information. These will be turned into a series of header <meta>
190 tags that look something like this:
191
192 <meta name="keywords" content="pharaoh secret mummy">
193 <meta name="description" content="copyright 1996 King Tut">
194
195 To create an HTTP-EQUIV type of <meta> tag, use -head, described below.
196
197 The -style argument is used to incorporate cascading stylesheets into
198 your code. See the section on CASCADING STYLESHEETS for more
199 information.
200
201 The -lang argument is used to incorporate a language attribute into the
202 <html> tag. For example:
203
204 print $q->start_html( -lang => 'fr-CA' );
205
206 The default if not specified is "en-US" for US English, unless the -dtd
207 parameter specifies an HTML 2.0 or 3.2 DTD, in which case the lang
208 attribute is left off. You can force the lang attribute to left off in
209 other cases by passing an empty string (-lang=>'').
210
211 The -encoding argument can be used to specify the character set for
212 XHTML. It defaults to iso-8859-1 if not specified.
213
214 The -dtd argument can be used to specify a public DTD identifier
215 string. For example:
216
217 -dtd => '-//W3C//DTD HTML 4.01 Transitional//EN')
218
219 Alternatively, it can take public and system DTD identifiers as an
220 array:
221
222 -dtd => [
223 '-//W3C//DTD HTML 4.01 Transitional//EN',
224 'http://www.w3.org/TR/html4/loose.dtd'
225 ]
226
227 For the public DTD identifier to be considered, it must be valid.
228 Otherwise it will be replaced by the default DTD. If the public DTD
229 contains 'XHTML', CGI.pm will emit XML.
230
231 The -declare_xml argument, when used in conjunction with XHTML, will
232 put a <?xml> declaration at the top of the HTML header. The sole
233 purpose of this declaration is to declare the character set encoding.
234 In the absence of -declare_xml, the output HTML will contain a <meta>
235 tag that specifies the encoding, allowing the HTML to pass most
236 validators. The default for -declare_xml is false.
237
238 You can place other arbitrary HTML elements to the <head> section with
239 the -head tag. For example, to place a <link> element in the head
240 section, use this:
241
242 print start_html(
243 -head => Link({
244 -rel => 'shortcut icon',
245 -href => 'favicon.ico'
246 })
247 );
248
249 To incorporate multiple HTML elements into the <head> section, just
250 pass an array reference:
251
252 print start_html(
253 -head => [
254 Link({
255 -rel => 'next',
256 -href => 'http://www.capricorn.com/s2.html'
257 }),
258 Link({
259 -rel => 'previous',
260 -href => 'http://www.capricorn.com/s1.html'
261 })
262 ]
263 );
264
265 And here's how to create an HTTP-EQUIV <meta> tag:
266
267 print start_html(
268 -head => meta({
269 -http_equiv => 'Content-Type',
270 -content => 'text/html'
271 })
272 );
273
274 JAVASCRIPTING: The -script, -noScript, -onLoad, -onMouseOver,
275 -onMouseOut and -onUnload parameters are used to add JavaScript calls
276 to your pages. -script should point to a block of text containing
277 JavaScript function definitions. This block will be placed within a
278 <script> block inside the HTML (not HTTP) header. The block is placed
279 in the header in order to give your page a fighting chance of having
280 all its JavaScript functions in place even if the user presses the stop
281 button before the page has loaded completely. CGI.pm attempts to format
282 the script in such a way that JavaScript-naive browsers will not choke
283 on the code: unfortunately there are some browsers that get confused by
284 it nevertheless.
285
286 The -onLoad and -onUnload parameters point to fragments of JavaScript
287 code to execute when the page is respectively opened and closed by the
288 browser. Usually these parameters are calls to functions defined in
289 the -script field:
290
291 $q = CGI->new;
292 print header;
293 $JSCRIPT = <<END;
294 // Ask a silly question
295 function riddle_me_this() {
296 var r = prompt(
297 "What walks on four legs in the morning, " +
298 "two legs in the afternoon, " +
299 "and three legs in the evening?"
300 );
301 response(r);
302 }
303 // Get a silly answer
304 function response(answer) {
305 if (answer == "man")
306 alert("Right you are!");
307 else
308 alert("Wrong! Guess again.");
309 }
310 END
311 print start_html(
312 -title => 'The Riddle of the Sphinx',
313 -script => $JSCRIPT
314 );
315
316 Use the -noScript parameter to pass some HTML text that will be
317 displayed on browsers that do not have JavaScript (or browsers where
318 JavaScript is turned off).
319
320 The <script> tag, has several attributes including "type", "charset"
321 and "src". "src" allows you to keep JavaScript code in an external
322 file. To use these attributes pass a HASH reference in the -script
323 parameter containing one or more of -type, -src, or -code:
324
325 print $q->start_html(
326 -title => 'The Riddle of the Sphinx',
327 -script => {
328 -type => 'JAVASCRIPT',
329 -src => '/javascript/sphinx.js'}
330 );
331
332 print $q->(
333 -title => 'The Riddle of the Sphinx',
334 -script => {
335 -type => 'PERLSCRIPT',
336 -code => 'print "hello world!\n;"'
337 }
338 );
339
340 A final feature allows you to incorporate multiple <script> sections
341 into the header. Just pass the list of script sections as an array
342 reference. This allows you to specify different source files for
343 different dialects of JavaScript. Example:
344
345 print $q->start_html(
346 -title => 'The Riddle of the Sphinx',
347 -script => [
348 {
349 -type => 'text/javascript',
350 -src => '/javascript/utilities10.js'
351 },
352 {
353 -type => 'text/javascript',
354 -src => '/javascript/utilities11.js'
355 },
356 {
357 -type => 'text/jscript',
358 -src => '/javascript/utilities12.js'
359 },
360 {
361 -type => 'text/ecmascript',
362 -src => '/javascript/utilities219.js'
363 }
364 ]
365 );
366
367 The option "-language" is a synonym for -type, and is supported for
368 backwards compatibility.
369
370 The old-style positional parameters are as follows:
371
372 Parameters:
373
374 1. The title
375
376 2. The author's e-mail address (will create a <link rev="MADE"> tag if
377 present
378
379 3. A 'true' flag if you want to include a <base> tag in the header.
380 This helps resolve relative addresses to absolute ones when the
381 document is moved, but makes the document hierarchy non-portable.
382 Use with care!
383
384 Other parameters you want to include in the <body> tag may be appended
385 to these. This is a good place to put HTML extensions, such as colors
386 and wallpaper patterns.
387
388 Ending the Html document:
389 print $q->end_html;
390
391 This ends an HTML document by printing the </body></html> tags.
392
394 CGI.pm defines general HTML shortcut methods for many HTML tags. HTML
395 shortcuts are named after a single HTML element and return a fragment
396 of HTML text. Example:
397
398 print $q->blockquote(
399 "Many years ago on the island of",
400 $q->a({href=>"http://crete.org/"},"Crete"),
401 "there lived a Minotaur named",
402 $q->strong("Fred."),
403 ),
404 $q->hr;
405
406 This results in the following HTML code (extra newlines have been added
407 for readability):
408
409 <blockquote>
410 Many years ago on the island of
411 <a href="http://crete.org/">Crete</a> there lived
412 a minotaur named <strong>Fred.</strong>
413 </blockquote>
414 <hr>
415
416 If you find the syntax for calling the HTML shortcuts awkward, you can
417 import them into your namespace and dispense with the object syntax
418 completely (see the next section for more details):
419
420 use CGI ':standard';
421 print blockquote(
422 "Many years ago on the island of",
423 a({href=>"http://crete.org/"},"Crete"),
424 "there lived a minotaur named",
425 strong("Fred."),
426 ),
427 hr;
428
429 Providing arguments to HTML shortcuts
430 The HTML methods will accept zero, one or multiple arguments. If you
431 provide no arguments, you get a single tag:
432
433 print hr; # <hr>
434
435 If you provide one or more string arguments, they are concatenated
436 together with spaces and placed between opening and closing tags:
437
438 print h1("Chapter","1"); # <h1>Chapter 1</h1>"
439
440 If the first argument is a hash reference, then the keys and values of
441 the hash become the HTML tag's attributes:
442
443 print a({-href=>'fred.html',-target=>'_new'},
444 "Open a new frame");
445
446 <a href="fred.html",target="_new">Open a new frame</a>
447
448 You may dispense with the dashes in front of the attribute names if you
449 prefer:
450
451 print img {src=>'fred.gif',align=>'LEFT'};
452
453 <img align="LEFT" src="fred.gif">
454
455 Sometimes an HTML tag attribute has no argument. For example, ordered
456 lists can be marked as COMPACT. The syntax for this is an argument
457 that that points to an undef string:
458
459 print ol({compact=>undef},li('one'),li('two'),li('three'));
460
461 Prior to CGI.pm version 2.41, providing an empty ('') string as an
462 attribute argument was the same as providing undef. However, this has
463 changed in order to accommodate those who want to create tags of the
464 form <img alt="">. The difference is shown in these two pieces of
465 code:
466
467 CODE RESULT
468 img({alt=>undef}) <img alt>
469 img({alt=>''}) <img alt="">
470
471 The distributive property of HTML shortcuts
472 One of the cool features of the HTML shortcuts is that they are
473 distributive. If you give them an argument consisting of a reference
474 to a list, the tag will be distributed across each element of the list.
475 For example, here's one way to make an ordered list:
476
477 print ul(
478 li({-type=>'disc'},['Sneezy','Doc','Sleepy','Happy'])
479 );
480
481 This example will result in HTML output that looks like this:
482
483 <ul>
484 <li type="disc">Sneezy</li>
485 <li type="disc">Doc</li>
486 <li type="disc">Sleepy</li>
487 <li type="disc">Happy</li>
488 </ul>
489
490 This is extremely useful for creating tables. For example:
491
492 print table({-border=>undef},
493 caption('When Should You Eat Your Vegetables?'),
494 Tr({-align=>'CENTER',-valign=>'TOP'},
495 [
496 th(['Vegetable', 'Breakfast','Lunch','Dinner']),
497 td(['Tomatoes' , 'no', 'yes', 'yes']),
498 td(['Broccoli' , 'no', 'no', 'yes']),
499 td(['Onions' , 'yes','yes', 'yes'])
500 ]
501 )
502 );
503
504 HTML shortcuts and list interpolation
505 Consider this bit of code:
506
507 print blockquote(em('Hi'),'mom!'));
508
509 It will ordinarily return the string that you probably expect, namely:
510
511 <blockquote><em>Hi</em> mom!</blockquote>
512
513 Note the space between the element "Hi" and the element "mom!". CGI.pm
514 puts the extra space there using array interpolation, which is
515 controlled by the magic $" variable. Sometimes this extra space is not
516 what you want, for example, when you are trying to align a series of
517 images. In this case, you can simply change the value of $" to an
518 empty string.
519
520 {
521 local($") = '';
522 print blockquote(em('Hi'),'mom!'));
523 }
524
525 I suggest you put the code in a block as shown here. Otherwise the
526 change to $" will affect all subsequent code until you explicitly reset
527 it.
528
529 Non-standard HTML shortcuts
530 A few HTML tags don't follow the standard pattern for various reasons.
531
532 comment() generates an HTML comment (<!-- comment -->). Call it like
533
534 print comment('here is my comment');
535
536 Because of conflicts with built-in perl functions, the following
537 functions begin with initial caps:
538
539 Select
540 Tr
541 Link
542 Delete
543 Accept
544 Sub
545
546 In addition, start_html(), end_html(), start_form(), end_form(),
547 start_multipart_form() and all the fill-out form tags are special. See
548 their respective sections.
549
550 Autoescaping HTML
551 By default, all HTML that is emitted by the form-generating functions
552 is passed through a function called escapeHTML():
553
554 $escaped_string = escapeHTML("unescaped string");
555 Escape HTML formatting characters in a string. Internally this
556 calls HTML::Entities (encode_entities) so really you should just
557 use that instead - the default list of chars that will be encoded
558 (passed to the HTML::Entities encode_entities method) is:
559
560 & < > " \x8b \x9b '
561
562 you can control this list by setting the value of
563 $CGI::ENCODE_ENTITIES:
564
565 # only encode < >
566 $CGI::ENCODE_ENTITIES = q{<>}
567
568 if you want to encode all entities then undef
569 $CGI::ENCODE_ENTITIES:
570
571 # encode all entities
572 $CGI::ENCODE_ENTITIES = undef;
573
574 The automatic escaping does not apply to other shortcuts, such as h1().
575 You should call escapeHTML() yourself on untrusted data in order to
576 protect your pages against nasty tricks that people may enter into
577 guestbooks, etc.. To change the character set, use charset(). To turn
578 autoescaping off completely, use autoEscape(0):
579
580 $charset = charset([$charset]);
581 Get or set the current character set.
582
583 $flag = autoEscape([$flag]);
584 Get or set the value of the autoescape flag.
585
587 General note The various form-creating methods all return strings to
588 the caller, containing the tag or tags that will create the requested
589 form element. You are responsible for actually printing out these
590 strings. It's set up this way so that you can place formatting tags
591 around the form elements.
592
593 Another note The default values that you specify for the forms are only
594 used the first time the script is invoked (when there is no query
595 string). On subsequent invocations of the script (when there is a
596 query string), the former values are used even if they are blank.
597
598 If you want to change the value of a field from its previous value, you
599 have two choices:
600
601 (1) call the param() method to set it.
602
603 (2) use the -override (alias -force) parameter (a new feature in
604 version 2.15). This forces the default value to be used, regardless of
605 the previous value:
606
607 print textfield(-name=>'field_name',
608 -default=>'starting value',
609 -override=>1,
610 -size=>50,
611 -maxlength=>80);
612
613 Yet another note By default, the text and labels of form elements are
614 escaped according to HTML rules. This means that you can safely use
615 "<CLICK ME>" as the label for a button. However, it also interferes
616 with your ability to incorporate special HTML character sequences, such
617 as Á, into your fields. If you wish to turn off automatic
618 escaping, call the autoEscape() method with a false value immediately
619 after creating the CGI object:
620
621 $q = CGI->new;
622 $q->autoEscape(0);
623
624 Note that autoEscape() is exclusively used to effect the behavior of
625 how some CGI.pm HTML generation functions handle escaping. Calling
626 escapeHTML() explicitly will always escape the HTML.
627
628 A Lurking Trap! Some of the form-element generating methods return
629 multiple tags. In a scalar context, the tags will be concatenated
630 together with spaces, or whatever is the current value of the $"
631 global. In a list context, the methods will return a list of elements,
632 allowing you to modify them if you wish. Usually you will not notice
633 this behavior, but beware of this:
634
635 printf("%s\n",end_form())
636
637 end_form() produces several tags, and only the first of them will be
638 printed because the format only expects one value.
639
640 <p>
641
642 Creating an isindex tag
643 print isindex(-action=>$action);
644
645 -or-
646
647 print isindex($action);
648
649 Prints out an <isindex> tag. Not very exciting. The parameter -action
650 specifies the URL of the script to process the query. The default is
651 to process the query with the current script.
652
653 Starting and ending a form
654 print start_form(-method=>$method,
655 -action=>$action,
656 -enctype=>$encoding);
657 <... various form stuff ...>
658 print end_form;
659
660 -or-
661
662 print start_form($method,$action,$encoding);
663 <... various form stuff ...>
664 print end_form;
665
666 start_form() will return a <form> tag with the optional method, action
667 and form encoding that you specify. The defaults are:
668
669 method: POST
670 action: this script
671 enctype: application/x-www-form-urlencoded for non-XHTML
672 multipart/form-data for XHTML, see multipart/form-data below.
673
674 end_form() returns the closing </form> tag.
675
676 start_form()'s enctype argument tells the browser how to package the
677 various fields of the form before sending the form to the server. Two
678 values are possible:
679
680 application/x-www-form-urlencoded
681 This is the older type of encoding. It is compatible with many CGI
682 scripts and is suitable for short fields containing text data. For
683 your convenience, CGI.pm stores the name of this encoding type in
684 &CGI::URL_ENCODED.
685
686 multipart/form-data
687 This is the newer type of encoding. It is suitable for forms that
688 contain very large fields or that are intended for transferring
689 binary data. Most importantly, it enables the "file upload"
690 feature. For your convenience, CGI.pm stores the name of this
691 encoding type in &CGI::MULTIPART
692
693 Forms that use this type of encoding are not easily interpreted by
694 CGI scripts unless they use CGI.pm or another library designed to
695 handle them.
696
697 If XHTML is activated (the default), then forms will be
698 automatically created using this type of encoding.
699
700 The start_form() method uses the older form of encoding by default
701 unless XHTML is requested. If you want to use the newer form of
702 encoding by default, you can call start_multipart_form() instead of
703 start_form(). The method end_multipart_form() is an alias to
704 end_form().
705
706 JAVASCRIPTING: The -name and -onSubmit parameters are provided for use
707 with JavaScript. The -name parameter gives the form a name so that it
708 can be identified and manipulated by JavaScript functions. -onSubmit
709 should point to a JavaScript function that will be executed just before
710 the form is submitted to your server. You can use this opportunity to
711 check the contents of the form for consistency and completeness. If
712 you find something wrong, you can put up an alert box or maybe fix
713 things up yourself. You can abort the submission by returning false
714 from this function.
715
716 Usually the bulk of JavaScript functions are defined in a <script>
717 block in the HTML header and -onSubmit points to one of these function
718 call. See start_html() for details.
719
720 Form elements
721 After starting a form, you will typically create one or more
722 textfields, popup menus, radio groups and other form elements. Each of
723 these elements takes a standard set of named arguments. Some elements
724 also have optional arguments. The standard arguments are as follows:
725
726 -name
727 The name of the field. After submission this name can be used to
728 retrieve the field's value using the param() method.
729
730 -value, -values
731 The initial value of the field which will be returned to the script
732 after form submission. Some form elements, such as text fields,
733 take a single scalar -value argument. Others, such as popup menus,
734 take a reference to an array of values. The two arguments are
735 synonyms.
736
737 -tabindex
738 A numeric value that sets the order in which the form element
739 receives focus when the user presses the tab key. Elements with
740 lower values receive focus first.
741
742 -id A string identifier that can be used to identify this element to
743 JavaScript and DHTML.
744
745 -override
746 A boolean, which, if true, forces the element to take on the value
747 specified by -value, overriding the sticky behavior described
748 earlier for the -nosticky pragma.
749
750 -onChange, -onFocus, -onBlur, -onMouseOver, -onMouseOut, -onSelect
751 These are used to assign JavaScript event handlers. See the
752 JavaScripting section for more details.
753
754 Other common arguments are described in the next section. In addition
755 to these, all attributes described in the HTML specifications are
756 supported.
757
758 Creating a text field
759 print textfield(-name=>'field_name',
760 -value=>'starting value',
761 -size=>50,
762 -maxlength=>80);
763 -or-
764
765 print textfield('field_name','starting value',50,80);
766
767 textfield() will return a text input field.
768
769 Parameters
770
771 1. The first parameter is the required name for the field (-name).
772
773 2. The optional second parameter is the default starting value for the
774 field contents (-value, formerly known as -default).
775
776 3. The optional third parameter is the size of the field in
777 characters (-size).
778
779 4. The optional fourth parameter is the maximum number of characters
780 the
781 field will accept (-maxlength).
782
783 As with all these methods, the field will be initialized with its
784 previous contents from earlier invocations of the script. When the
785 form is processed, the value of the text field can be retrieved with:
786
787 $value = param('foo');
788
789 If you want to reset it from its initial value after the script has
790 been called once, you can do so like this:
791
792 param('foo',"I'm taking over this value!");
793
794 Creating a big text field
795 print textarea(-name=>'foo',
796 -default=>'starting value',
797 -rows=>10,
798 -columns=>50);
799
800 -or
801
802 print textarea('foo','starting value',10,50);
803
804 textarea() is just like textfield, but it allows you to specify rows
805 and columns for a multiline text entry box. You can provide a starting
806 value for the field, which can be long and contain multiple lines.
807
808 Creating a password field
809 print password_field(-name=>'secret',
810 -value=>'starting value',
811 -size=>50,
812 -maxlength=>80);
813 -or-
814
815 print password_field('secret','starting value',50,80);
816
817 password_field() is identical to textfield(), except that its contents
818 will be starred out on the web page.
819
820 Creating a file upload field
821 print filefield(-name=>'uploaded_file',
822 -default=>'starting value',
823 -size=>50,
824 -maxlength=>80);
825 -or-
826
827 print filefield('uploaded_file','starting value',50,80);
828
829 filefield() will return a file upload field. In order to take full
830 advantage of this you must use the new multipart encoding scheme for
831 the form. You can do this either by calling start_form() with an
832 encoding type of &CGI::MULTIPART, or by calling the new method
833 start_multipart_form() instead of vanilla start_form().
834
835 Parameters
836
837 1. The first parameter is the required name for the field (-name).
838
839 2. The optional second parameter is the starting value for the field
840 contents to be used as the default file name (-default).
841
842 For security reasons, browsers don't pay any attention to this
843 field, and so the starting value will always be blank. Worse, the
844 field loses its "sticky" behavior and forgets its previous
845 contents. The starting value field is called for in the HTML
846 specification, however, and possibly some browser will eventually
847 provide support for it.
848
849 3. The optional third parameter is the size of the field in characters
850 (-size).
851
852 4. The optional fourth parameter is the maximum number of characters
853 the field will accept (-maxlength).
854
855 JAVASCRIPTING: The -onChange, -onFocus, -onBlur, -onMouseOver,
856 -onMouseOut and -onSelect parameters are recognized. See textfield()
857 for details.
858
859 Creating a popup menu
860 print popup_menu('menu_name',
861 ['eenie','meenie','minie'],
862 'meenie');
863
864 -or-
865
866 %labels = ('eenie'=>'your first choice',
867 'meenie'=>'your second choice',
868 'minie'=>'your third choice');
869 %attributes = ('eenie'=>{'class'=>'class of first choice'});
870 print popup_menu('menu_name',
871 ['eenie','meenie','minie'],
872 'meenie',\%labels,\%attributes);
873
874 -or (named parameter style)-
875
876 print popup_menu(-name=>'menu_name',
877 -values=>['eenie','meenie','minie'],
878 -default=>['meenie','minie'],
879 -labels=>\%labels,
880 -attributes=>\%attributes);
881
882 popup_menu() creates a menu. Please note that the -multiple option will
883 be ignored if passed - use scrolling_list() if you want to create a
884 menu that supports multiple selections
885
886 1. The required first argument is the menu's name (-name).
887
888 2. The required second argument (-values) is an array reference
889 containing the list of menu items in the menu. You can pass the
890 method an anonymous array, as shown in the example, or a reference
891 to a named array, such as "\@foo".
892
893 3. The optional third parameter (-default) is the name of the default
894 menu choice. If not specified, the first item will be the default.
895 The values of the previous choice will be maintained across
896 queries. Pass an array reference to select multiple defaults.
897
898 4. The optional fourth parameter (-labels) is provided for people who
899 want to use different values for the user-visible label inside the
900 popup menu and the value returned to your script. It's a pointer
901 to an hash relating menu values to user-visible labels. If you
902 leave this parameter blank, the menu values will be displayed by
903 default. (You can also leave a label undefined if you want to).
904
905 5. The optional fifth parameter (-attributes) is provided to assign
906 any of the common HTML attributes to an individual menu item. It's
907 a pointer to a hash relating menu values to another hash with the
908 attribute's name as the key and the attribute's value as the value.
909
910 When the form is processed, the selected value of the popup menu can be
911 retrieved using:
912
913 $popup_menu_value = param('menu_name');
914
915 Creating an option group
916 Named parameter style
917
918 print popup_menu(-name=>'menu_name',
919 -values=>[qw/eenie meenie minie/,
920 optgroup(-name=>'optgroup_name',
921 -values => ['moe','catch'],
922 -attributes=>{'catch'=>{'class'=>'red'}})],
923 -labels=>{'eenie'=>'one',
924 'meenie'=>'two',
925 'minie'=>'three'},
926 -default=>'meenie');
927
928 Old style
929 print popup_menu('menu_name',
930 ['eenie','meenie','minie',
931 optgroup('optgroup_name', ['moe', 'catch'],
932 {'catch'=>{'class'=>'red'}})],'meenie',
933 {'eenie'=>'one','meenie'=>'two','minie'=>'three'});
934
935 optgroup() creates an option group within a popup menu.
936
937 1. The required first argument (-name) is the label attribute of the
938 optgroup and is not inserted in the parameter list of the query.
939
940 2. The required second argument (-values) is an array reference
941 containing the list of menu items in the menu. You can pass the
942 method an anonymous array, as shown in the example, or a reference
943 to a named array, such as \@foo. If you pass a HASH reference, the
944 keys will be used for the menu values, and the values will be used
945 for the menu labels (see -labels below).
946
947 3. The optional third parameter (-labels) allows you to pass a
948 reference to a hash containing user-visible labels for one or more
949 of the menu items. You can use this when you want the user to see
950 one menu string, but have the browser return your program a
951 different one. If you don't specify this, the value string will be
952 used instead ("eenie", "meenie" and "minie" in this example). This
953 is equivalent to using a hash reference for the -values parameter.
954
955 4. An optional fourth parameter (-labeled) can be set to a true value
956 and indicates that the values should be used as the label attribute
957 for each option element within the optgroup.
958
959 5. An optional fifth parameter (-novals) can be set to a true value
960 and indicates to suppress the val attribute in each option element
961 within the optgroup.
962
963 See the discussion on optgroup at W3C
964 (http://www.w3.org/TR/REC-html40/interact/forms.html#edef-OPTGROUP)
965 for details.
966
967 6. An optional sixth parameter (-attributes) is provided to assign any
968 of the common HTML attributes to an individual menu item. It's a
969 pointer to a hash relating menu values to another hash with the
970 attribute's name as the key and the attribute's value as the value.
971
972 Creating a scrolling list
973 print scrolling_list('list_name',
974 ['eenie','meenie','minie','moe'],
975 ['eenie','moe'],5,'true',{'moe'=>{'class'=>'red'}});
976 -or-
977
978 print scrolling_list('list_name',
979 ['eenie','meenie','minie','moe'],
980 ['eenie','moe'],5,'true',
981 \%labels,%attributes);
982
983 -or-
984
985 print scrolling_list(-name=>'list_name',
986 -values=>['eenie','meenie','minie','moe'],
987 -default=>['eenie','moe'],
988 -size=>5,
989 -multiple=>'true',
990 -labels=>\%labels,
991 -attributes=>\%attributes);
992
993 scrolling_list() creates a scrolling list.
994
995 Parameters:
996
997 1. The first and second arguments are the list name (-name) and values
998 (-values). As in the popup menu, the second argument should be an
999 array reference.
1000
1001 2. The optional third argument (-default) can be either a reference to
1002 a list containing the values to be selected by default, or can be a
1003 single value to select. If this argument is missing or undefined,
1004 then nothing is selected when the list first appears. In the named
1005 parameter version, you can use the synonym "-defaults" for this
1006 parameter.
1007
1008 3. The optional fourth argument is the size of the list (-size).
1009
1010 4. The optional fifth argument can be set to true to allow multiple
1011 simultaneous selections (-multiple). Otherwise only one selection
1012 will be allowed at a time.
1013
1014 5. The optional sixth argument is a pointer to a hash containing long
1015 user-visible labels for the list items (-labels). If not provided,
1016 the values will be displayed.
1017
1018 6. The optional sixth parameter (-attributes) is provided to assign
1019 any of the common HTML attributes to an individual menu item. It's
1020 a pointer to a hash relating menu values to another hash with the
1021 attribute's name as the key and the attribute's value as the value.
1022
1023 When this form is processed, all selected list items will be
1024 returned as a list under the parameter name 'list_name'. The
1025 values of the selected items can be retrieved with:
1026
1027 @selected = param('list_name');
1028
1029 Creating a group of related checkboxes
1030 print checkbox_group(-name=>'group_name',
1031 -values=>['eenie','meenie','minie','moe'],
1032 -default=>['eenie','moe'],
1033 -linebreak=>'true',
1034 -disabled => ['moe'],
1035 -labels=>\%labels,
1036 -attributes=>\%attributes);
1037
1038 print checkbox_group('group_name',
1039 ['eenie','meenie','minie','moe'],
1040 ['eenie','moe'],'true',\%labels,
1041 {'moe'=>{'class'=>'red'}});
1042
1043 HTML3-COMPATIBLE BROWSERS ONLY:
1044
1045 print checkbox_group(-name=>'group_name',
1046 -values=>['eenie','meenie','minie','moe'],
1047 -rows=2,-columns=>2);
1048
1049 checkbox_group() creates a list of checkboxes that are related by the
1050 same name.
1051
1052 Parameters:
1053
1054 1. The first and second arguments are the checkbox name and values,
1055 respectively (-name and -values). As in the popup menu, the second
1056 argument should be an array reference. These values are used for
1057 the user-readable labels printed next to the checkboxes as well as
1058 for the values passed to your script in the query string.
1059
1060 2. The optional third argument (-default) can be either a reference to
1061 a list containing the values to be checked by default, or can be a
1062 single value to checked. If this argument is missing or undefined,
1063 then nothing is selected when the list first appears.
1064
1065 3. The optional fourth argument (-linebreak) can be set to true to
1066 place line breaks between the checkboxes so that they appear as a
1067 vertical list. Otherwise, they will be strung together on a
1068 horizontal line.
1069
1070 The optional -labels argument is a pointer to a hash relating the
1071 checkbox values to the user-visible labels that will be printed next to
1072 them. If not provided, the values will be used as the default.
1073
1074 The optional parameters -rows, and -columns cause checkbox_group() to
1075 return an HTML3 compatible table containing the checkbox group
1076 formatted with the specified number of rows and columns. You can
1077 provide just the -columns parameter if you wish; checkbox_group will
1078 calculate the correct number of rows for you.
1079
1080 The option -disabled takes an array of checkbox values and disables
1081 them by greying them out (this may not be supported by all browsers).
1082
1083 The optional -attributes argument is provided to assign any of the
1084 common HTML attributes to an individual menu item. It's a pointer to a
1085 hash relating menu values to another hash with the attribute's name as
1086 the key and the attribute's value as the value.
1087
1088 The optional -tabindex argument can be used to control the order in
1089 which radio buttons receive focus when the user presses the tab button.
1090 If passed a scalar numeric value, the first element in the group will
1091 receive this tab index and subsequent elements will be incremented by
1092 one. If given a reference to an array of radio button values, then the
1093 indexes will be jiggered so that the order specified in the array will
1094 correspond to the tab order. You can also pass a reference to a hash
1095 in which the hash keys are the radio button values and the values are
1096 the tab indexes of each button. Examples:
1097
1098 -tabindex => 100 # this group starts at index 100 and counts up
1099 -tabindex => ['moe','minie','eenie','meenie'] # tab in this order
1100 -tabindex => {meenie=>100,moe=>101,minie=>102,eenie=>200} # tab in this order
1101
1102 The optional -labelattributes argument will contain attributes attached
1103 to the <label> element that surrounds each button.
1104
1105 When the form is processed, all checked boxes will be returned as a
1106 list under the parameter name 'group_name'. The values of the "on"
1107 checkboxes can be retrieved with:
1108
1109 @turned_on = param('group_name');
1110
1111 The value returned by checkbox_group() is actually an array of button
1112 elements. You can capture them and use them within tables, lists, or
1113 in other creative ways:
1114
1115 @h = checkbox_group(-name=>'group_name',-values=>\@values);
1116 &use_in_creative_way(@h);
1117
1118 Creating a standalone checkbox
1119 print checkbox(-name=>'checkbox_name',
1120 -checked=>1,
1121 -value=>'ON',
1122 -label=>'CLICK ME');
1123
1124 -or-
1125
1126 print checkbox('checkbox_name','checked','ON','CLICK ME');
1127
1128 checkbox() is used to create an isolated checkbox that isn't logically
1129 related to any others.
1130
1131 Parameters:
1132
1133 1. The first parameter is the required name for the checkbox (-name).
1134 It will also be used for the user-readable label printed next to
1135 the checkbox.
1136
1137 2. The optional second parameter (-checked) specifies that the
1138 checkbox is turned on by default. Synonyms are -selected and -on.
1139
1140 3. The optional third parameter (-value) specifies the value of the
1141 checkbox when it is checked. If not provided, the word "on" is
1142 assumed.
1143
1144 4. The optional fourth parameter (-label) is the user-readable label
1145 to be attached to the checkbox. If not provided, the checkbox name
1146 is used.
1147
1148 The value of the checkbox can be retrieved using:
1149
1150 $turned_on = param('checkbox_name');
1151
1152 Creating a radio button group
1153 print radio_group(-name=>'group_name',
1154 -values=>['eenie','meenie','minie'],
1155 -default=>'meenie',
1156 -linebreak=>'true',
1157 -labels=>\%labels,
1158 -attributes=>\%attributes);
1159
1160 -or-
1161
1162 print radio_group('group_name',['eenie','meenie','minie'],
1163 'meenie','true',\%labels,\%attributes);
1164
1165
1166 HTML3-COMPATIBLE BROWSERS ONLY:
1167
1168 print radio_group(-name=>'group_name',
1169 -values=>['eenie','meenie','minie','moe'],
1170 -rows=2,-columns=>2);
1171
1172 radio_group() creates a set of logically-related radio buttons (turning
1173 one member of the group on turns the others off)
1174
1175 Parameters:
1176
1177 1. The first argument is the name of the group and is required
1178 (-name).
1179
1180 2. The second argument (-values) is the list of values for the radio
1181 buttons. The values and the labels that appear on the page are
1182 identical. Pass an array reference in the second argument, either
1183 using an anonymous array, as shown, or by referencing a named array
1184 as in "\@foo".
1185
1186 3. The optional third parameter (-default) is the name of the default
1187 button to turn on. If not specified, the first item will be the
1188 default. You can provide a nonexistent button name, such as "-" to
1189 start up with no buttons selected.
1190
1191 4. The optional fourth parameter (-linebreak) can be set to 'true' to
1192 put line breaks between the buttons, creating a vertical list.
1193
1194 5. The optional fifth parameter (-labels) is a pointer to an
1195 associative array relating the radio button values to user-visible
1196 labels to be used in the display. If not provided, the values
1197 themselves are displayed.
1198
1199 All modern browsers can take advantage of the optional parameters
1200 -rows, and -columns. These parameters cause radio_group() to return an
1201 HTML3 compatible table containing the radio group formatted with the
1202 specified number of rows and columns. You can provide just the
1203 -columns parameter if you wish; radio_group will calculate the correct
1204 number of rows for you.
1205
1206 To include row and column headings in the returned table, you can use
1207 the -rowheaders and -colheaders parameters. Both of these accept a
1208 pointer to an array of headings to use. The headings are just
1209 decorative. They don't reorganize the interpretation of the radio
1210 buttons -- they're still a single named unit.
1211
1212 The optional -tabindex argument can be used to control the order in
1213 which radio buttons receive focus when the user presses the tab button.
1214 If passed a scalar numeric value, the first element in the group will
1215 receive this tab index and subsequent elements will be incremented by
1216 one. If given a reference to an array of radio button values, then the
1217 indexes will be jiggered so that the order specified in the array will
1218 correspond to the tab order. You can also pass a reference to a hash
1219 in which the hash keys are the radio button values and the values are
1220 the tab indexes of each button. Examples:
1221
1222 -tabindex => 100 # this group starts at index 100 and counts up
1223 -tabindex => ['moe','minie','eenie','meenie'] # tab in this order
1224 -tabindex => {meenie=>100,moe=>101,minie=>102,eenie=>200} # tab in this order
1225
1226 The optional -attributes argument is provided to assign any of the
1227 common HTML attributes to an individual menu item. It's a pointer to a
1228 hash relating menu values to another hash with the attribute's name as
1229 the key and the attribute's value as the value.
1230
1231 The optional -labelattributes argument will contain attributes attached
1232 to the <label> element that surrounds each button.
1233
1234 When the form is processed, the selected radio button can be retrieved
1235 using:
1236
1237 $which_radio_button = param('group_name');
1238
1239 The value returned by radio_group() is actually an array of button
1240 elements. You can capture them and use them within tables, lists, or
1241 in other creative ways:
1242
1243 @h = radio_group(-name=>'group_name',-values=>\@values);
1244 &use_in_creative_way(@h);
1245
1246 Creating a submit button
1247 print submit(-name=>'button_name',
1248 -value=>'value');
1249
1250 -or-
1251
1252 print submit('button_name','value');
1253
1254 submit() will create the query submission button. Every form should
1255 have one of these.
1256
1257 Parameters:
1258
1259 1. The first argument (-name) is optional. You can give the button a
1260 name if you have several submission buttons in your form and you
1261 want to distinguish between them.
1262
1263 2. The second argument (-value) is also optional. This gives the
1264 button a value that will be passed to your script in the query
1265 string. The name will also be used as the user-visible label.
1266
1267 3. You can use -label as an alias for -value. I always get confused
1268 about which of -name and -value changes the user-visible label on
1269 the button.
1270
1271 You can figure out which button was pressed by using different values
1272 for each one:
1273
1274 $which_one = param('button_name');
1275
1276 Creating a reset button
1277 print reset
1278
1279 reset() creates the "reset" button. Note that it restores the form to
1280 its value from the last time the script was called, NOT necessarily to
1281 the defaults.
1282
1283 Note that this conflicts with the perl reset() built-in. Use
1284 CORE::reset() to get the original reset function.
1285
1286 Creating a default button
1287 print defaults('button_label')
1288
1289 defaults() creates a button that, when invoked, will cause the form to
1290 be completely reset to its defaults, wiping out all the changes the
1291 user ever made.
1292
1293 Creating a hidden field
1294 print hidden(-name=>'hidden_name',
1295 -default=>['value1','value2'...]);
1296
1297 -or-
1298
1299 print hidden('hidden_name','value1','value2'...);
1300
1301 hidden() produces a text field that can't be seen by the user. It is
1302 useful for passing state variable information from one invocation of
1303 the script to the next.
1304
1305 Parameters:
1306
1307 1. The first argument is required and specifies the name of this field
1308 (-name).
1309
1310 2. The second argument is also required and specifies its value
1311 (-default). In the named parameter style of calling, you can
1312 provide a single value here or a reference to a whole list
1313
1314 Fetch the value of a hidden field this way:
1315
1316 $hidden_value = param('hidden_name');
1317
1318 Note, that just like all the other form elements, the value of a hidden
1319 field is "sticky". If you want to replace a hidden field with some
1320 other values after the script has been called once you'll have to do it
1321 manually:
1322
1323 param('hidden_name','new','values','here');
1324
1325 Creating a clickable image button
1326 print image_button(-name=>'button_name',
1327 -src=>'/source/URL',
1328 -align=>'MIDDLE');
1329
1330 -or-
1331
1332 print image_button('button_name','/source/URL','MIDDLE');
1333
1334 image_button() produces a clickable image. When it's clicked on the
1335 position of the click is returned to your script as "button_name.x" and
1336 "button_name.y", where "button_name" is the name you've assigned to it.
1337
1338 Parameters:
1339
1340 1. The first argument (-name) is required and specifies the name of
1341 this field.
1342
1343 2. The second argument (-src) is also required and specifies the URL
1344
1345 3. The third option (-align, optional) is an alignment type, and may
1346 be TOP, BOTTOM or MIDDLE
1347
1348 Fetch the value of the button this way:
1349 $x = param('button_name.x');
1350 $y = param('button_name.y');
1351
1352 Creating a javascript action button
1353 print button(-name=>'button_name',
1354 -value=>'user visible label',
1355 -onClick=>"do_something()");
1356
1357 -or-
1358
1359 print button('button_name',"user visible value","do_something()");
1360
1361 button() produces an "<input>" tag with "type="button"". When it's
1362 pressed the fragment of JavaScript code pointed to by the -onClick
1363 parameter will be executed.
1364
1366 It's possible for CGI.pm scripts to write into several browser panels
1367 and windows using the HTML 4 frame mechanism. There are three
1368 techniques for defining new frames programmatically:
1369
1370 1. Create a <Frameset> document
1371 After writing out the HTTP header, instead of creating a standard
1372 HTML document using the start_html() call, create a <frameset>
1373 document that defines the frames on the page. Specify your
1374 script(s) (with appropriate parameters) as the SRC for each of the
1375 frames.
1376
1377 There is no specific support for creating <frameset> sections in
1378 CGI.pm, but the HTML is very simple to write.
1379
1380 2. Specify the destination for the document in the HTTP header
1381 You may provide a -target parameter to the header() method:
1382
1383 print header(-target=>'ResultsWindow');
1384
1385 This will tell the browser to load the output of your script into
1386 the frame named "ResultsWindow". If a frame of that name doesn't
1387 already exist, the browser will pop up a new window and load your
1388 script's document into that. There are a number of magic names
1389 that you can use for targets. See the HTML "<frame>" documentation
1390 for details.
1391
1392 3. Specify the destination for the document in the <form> tag
1393 You can specify the frame to load in the FORM tag itself. With
1394 CGI.pm it looks like this:
1395
1396 print start_form(-target=>'ResultsWindow');
1397
1398 When your script is reinvoked by the form, its output will be
1399 loaded into the frame named "ResultsWindow". If one doesn't
1400 already exist a new window will be created.
1401
1402 The script "frameset.cgi" in the examples directory shows one way to
1403 create pages in which the fill-out form and the response live in side-
1404 by-side frames.
1405
1407 The usual way to use JavaScript is to define a set of functions in a
1408 <SCRIPT> block inside the HTML header and then to register event
1409 handlers in the various elements of the page. Events include such
1410 things as the mouse passing over a form element, a button being
1411 clicked, the contents of a text field changing, or a form being
1412 submitted. When an event occurs that involves an element that has
1413 registered an event handler, its associated JavaScript code gets
1414 called.
1415
1416 The elements that can register event handlers include the <BODY> of an
1417 HTML document, hypertext links, all the various elements of a fill-out
1418 form, and the form itself. There are a large number of events, and each
1419 applies only to the elements for which it is relevant. Here is a
1420 partial list:
1421
1422 onLoad
1423 The browser is loading the current document. Valid in:
1424
1425 + The HTML <BODY> section only.
1426
1427 onUnload
1428 The browser is closing the current page or frame. Valid for:
1429
1430 + The HTML <BODY> section only.
1431
1432 onSubmit
1433 The user has pressed the submit button of a form. This event
1434 happens just before the form is submitted, and your function can
1435 return a value of false in order to abort the submission. Valid
1436 for:
1437
1438 + Forms only.
1439
1440 onClick
1441 The mouse has clicked on an item in a fill-out form. Valid for:
1442
1443 + Buttons (including submit, reset, and image buttons)
1444 + Checkboxes
1445 + Radio buttons
1446
1447 onChange
1448 The user has changed the contents of a field. Valid for:
1449
1450 + Text fields
1451 + Text areas
1452 + Password fields
1453 + File fields
1454 + Popup Menus
1455 + Scrolling lists
1456
1457 onFocus
1458 The user has selected a field to work with. Valid for:
1459
1460 + Text fields
1461 + Text areas
1462 + Password fields
1463 + File fields
1464 + Popup Menus
1465 + Scrolling lists
1466
1467 onBlur
1468 The user has deselected a field (gone to work somewhere else).
1469 Valid for:
1470
1471 + Text fields
1472 + Text areas
1473 + Password fields
1474 + File fields
1475 + Popup Menus
1476 + Scrolling lists
1477
1478 onSelect
1479 The user has changed the part of a text field that is selected.
1480 Valid for:
1481
1482 + Text fields
1483 + Text areas
1484 + Password fields
1485 + File fields
1486
1487 onMouseOver
1488 The mouse has moved over an element.
1489
1490 + Text fields
1491 + Text areas
1492 + Password fields
1493 + File fields
1494 + Popup Menus
1495 + Scrolling lists
1496
1497 onMouseOut
1498 The mouse has moved off an element.
1499
1500 + Text fields
1501 + Text areas
1502 + Password fields
1503 + File fields
1504 + Popup Menus
1505 + Scrolling lists
1506
1507 In order to register a JavaScript event handler with an HTML element,
1508 just use the event name as a parameter when you call the corresponding
1509 CGI method. For example, to have your validateAge() JavaScript code
1510 executed every time the textfield named "age" changes, generate the
1511 field like this:
1512
1513 print textfield(-name=>'age',-onChange=>"validateAge(this)");
1514
1515 This example assumes that you've already declared the validateAge()
1516 function by incorporating it into a <SCRIPT> block. The CGI.pm
1517 start_html() method provides a convenient way to create this section.
1518
1519 Similarly, you can create a form that checks itself over for
1520 consistency and alerts the user if some essential value is missing by
1521 creating it this way:
1522 print start_form(-onSubmit=>"validateMe(this)");
1523
1524 See the javascript.cgi script for a demonstration of how this all
1525 works.
1526
1528 CGI.pm has limited support for HTML3's cascading style sheets (css).
1529 To incorporate a stylesheet into your document, pass the start_html()
1530 method a -style parameter. The value of this parameter may be a
1531 scalar, in which case it is treated as the source URL for the
1532 stylesheet, or it may be a hash reference. In the latter case you
1533 should provide the hash with one or more of -src or -code. -src points
1534 to a URL where an externally-defined stylesheet can be found. -code
1535 points to a scalar value to be incorporated into a <style> section.
1536 Style definitions in -code override similarly-named ones in -src, hence
1537 the name "cascading."
1538
1539 You may also specify the type of the stylesheet by adding the optional
1540 -type parameter to the hash pointed to by -style. If not specified,
1541 the style defaults to 'text/css'.
1542
1543 To refer to a style within the body of your document, add the -class
1544 parameter to any HTML element:
1545
1546 print h1({-class=>'Fancy'},'Welcome to the Party');
1547
1548 Or define styles on the fly with the -style parameter:
1549
1550 print h1({-style=>'Color: red;'},'Welcome to Hell');
1551
1552 You may also use the new span() element to apply a style to a section
1553 of text:
1554
1555 print span({-style=>'Color: red;'},
1556 h1('Welcome to Hell'),
1557 "Where did that handbasket get to?"
1558 );
1559
1560 Note that you must import the ":html3" definitions to have the span()
1561 method available. Here's a quick and dirty example of using CSS's.
1562 See the CSS specification at http://www.w3.org/Style/CSS/ for more
1563 information.
1564
1565 use CGI qw/:standard :html3/;
1566
1567 #here's a stylesheet incorporated directly into the page
1568 $newStyle=<<END;
1569 <!--
1570 P.Tip {
1571 margin-right: 50pt;
1572 margin-left: 50pt;
1573 color: red;
1574 }
1575 P.Alert {
1576 font-size: 30pt;
1577 font-family: sans-serif;
1578 color: red;
1579 }
1580 -->
1581 END
1582 print header();
1583 print start_html( -title=>'CGI with Style',
1584 -style=>{-src=>'http://www.capricorn.com/style/st1.css',
1585 -code=>$newStyle}
1586 );
1587 print h1('CGI with Style'),
1588 p({-class=>'Tip'},
1589 "Better read the cascading style sheet spec before playing with this!"),
1590 span({-style=>'color: magenta'},
1591 "Look Mom, no hands!",
1592 p(),
1593 "Whooo wee!"
1594 );
1595 print end_html;
1596
1597 Pass an array reference to -code or -src in order to incorporate
1598 multiple stylesheets into your document.
1599
1600 Should you wish to incorporate a verbatim stylesheet that includes
1601 arbitrary formatting in the header, you may pass a -verbatim tag to the
1602 -style hash, as follows:
1603
1604 print start_html (-style => {-verbatim => '@import
1605 url("/server-common/css/'.$cssFile.'");',
1606 -src => '/server-common/css/core.css'});
1607
1608 This will generate an HTML header that contains this:
1609
1610 <link rel="stylesheet" type="text/css" href="/server-common/css/core.css">
1611 <style type="text/css">
1612 @import url("/server-common/css/main.css");
1613 </style>
1614
1615 Any additional arguments passed in the -style value will be
1616 incorporated into the <link> tag. For example:
1617
1618 start_html(-style=>{-src=>['/styles/print.css','/styles/layout.css'],
1619 -media => 'all'});
1620
1621 This will give:
1622
1623 <link rel="stylesheet" type="text/css" href="/styles/print.css" media="all"/>
1624 <link rel="stylesheet" type="text/css" href="/styles/layout.css" media="all"/>
1625
1626 <p>
1627
1628 To make more complicated <link> tags, use the Link() function and pass
1629 it to start_html() in the -head argument, as in:
1630
1631 @h = (Link({-rel=>'stylesheet',-type=>'text/css',-src=>'/ss/ss.css',-media=>'all'}),
1632 Link({-rel=>'stylesheet',-type=>'text/css',-src=>'/ss/fred.css',-media=>'paper'}));
1633 print start_html({-head=>\@h})
1634
1635 To create primary and "alternate" stylesheet, use the -alternate
1636 option:
1637
1638 start_html(-style=>{-src=>[
1639 {-src=>'/styles/print.css'},
1640 {-src=>'/styles/alt.css',-alternate=>1}
1641 ]
1642 });
1643
1644 Dumping out all the name/value pairs
1645 The Dump() method produces a string consisting of all the query's
1646 name/value pairs formatted nicely as a nested list. This is useful for
1647 debugging purposes:
1648
1649 print Dump
1650
1651 Produces something that looks like:
1652
1653 <ul>
1654 <li>name1
1655 <ul>
1656 <li>value1
1657 <li>value2
1658 </ul>
1659 <li>name2
1660 <ul>
1661 <li>value1
1662 </ul>
1663 </ul>
1664
1665 As a shortcut, you can interpolate the entire CGI object into a string
1666 and it will be replaced with the a nice HTML dump shown above:
1667
1668 $q=CGI->new;
1669 print "<h2>Current Values</h2> $q\n";
1670
1672 Address bug reports and comments to:
1673 <https://github.com/leejo/CGI.pm/issues>
1674
1675 See the <https://github.com/leejo/CGI.pm/blob/master/CONTRIBUTING.md>
1676 file for information on raising issues and contributing
1677
1678 The original bug tracker can be found at:
1679 <https://rt.cpan.org/Public/Dist/Display.html?Queue=CGI.pm>
1680
1682 CGI - The original source of this documentation / functionality
1683
1684
1685
1686perl v5.38.0 2023-10-03 CGI::HTML::Functions(3)