Merge branch 'patch-18' of https://github.com/gjones2/Freeside
[freeside.git] / httemplate / elements / checkbox-tristate.html
1 <%doc>
2 A tristate checkbox (with three values: true, false, and null).
3 Internally, this creates a checkbox, coupled via javascript to a hidden
4 field that actually contains the value.  For now, the only values these
5 can have are 1, 0, and empty.  Clicking the checkbox cycles between them.
6 </%doc>
7 <%shared>
8 my $init = 0;
9 </%shared>
10 % if ( !$init ) {
11 %   $init = 1;
12 <SCRIPT TYPE="text/javascript">
13 function tristate_onclick() {
14   var checkbox = this;
15   var input = checkbox.input;
16   if ( input.value == "" ) {
17     input.value = "0";
18     checkbox.checked = false;
19     checkbox.indeterminate = false;
20   } else if ( input.value == "0" ) {
21     input.value = "1";
22     checkbox.checked = true;
23     checkbox.indeterminate = false;
24   } else if ( input.value == "1" ) {
25     input.value = "";
26     checkbox.checked = true;
27     checkbox.indeterminate = true
28   }
29 }
30
31 var tristates = [];
32 var tristate_boxes = [];
33 window.onload = function() { // don't do this until all of the checkboxes exist
34 %#  tristates = document.getElementsByClassName('tristate'); # curse you, IE8
35   var all_inputs = document.getElementsByTagName('input');
36   for (var i=0; i < all_inputs.length; i++) {
37     if ( all_inputs[i].className == 'tristate' ) {
38       tristates.push(all_inputs[i]);
39     }
40   }
41   for (var i=0; i < tristates.length; i++) {
42     tristate_boxes[i] =
43       document.getElementById('checkbox_' + tristates[i].name);
44     // make sure they can find each other
45     tristate_boxes[i].input = tristates[i];
46     tristates[i].checkbox = tristate_boxes[i];
47     // set event handler
48     tristate_boxes[i].onclick = tristate_onclick;
49     // set initial value
50     if ( tristates[i].value == "" ) {
51       tristate_boxes[i].indeterminate = true
52     }
53     if ( tristates[i].value != "0" ) {
54       tristate_boxes[i].checked = true;
55     }
56   }
57 };
58 </SCRIPT>
59 % } # end of $init
60 <INPUT TYPE="hidden" NAME="<% $opt{field} %>"
61                      ID="<% $opt{id} %>"
62                      VALUE="<% $curr_value %>"
63                      CLASS="tristate">
64 <INPUT TYPE="checkbox" ID="checkbox_<%$opt{field}%>" CLASS="partial">
65 <%init>
66
67 my %opt = @_;
68
69 # might be useful but I'm not implementing it yet
70 #my $onchange = $opt{'onchange'}
71 #                 ? 'onChange="'. $opt{'onchange'}. '(this)"'
72 #                 : '';
73
74 $opt{'id'} ||= 'hidden_'.$opt{'field'};
75 my $curr_value = $opt{curr_value};
76 $curr_value = undef
77   unless $curr_value eq '0' or $curr_value eq '1';
78 </%init>