Note:

If you want to create a new page for developers, you should create it on the Moodle Developer Resource site.

The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Checkboxes: Show only selected

This article was inspired by the General Developer forum discussion on "Interface design input please").

The task at hand is to make a possibly long check list of teachers more handy by showing only the selected items:

JavaScript teacher list2.png JavaScript teacher list only selected.png

Nothing fancy, but a good opportunity to compare different approaches using JavaScript:

  1. Home made JavaScript
  2. Using YUI, Moodle's default JavaScript library
  3. Using jQuery, another very popular JavaScript library

Plain JavaScript

That is the original code. There's a lot of DOM traversal and node counting going on due to browser incompatibilities.

<script type="text/javascript">

   var teacherslist=document.getElementById('pe_teachers')
   if(teacherslist.childNodes[0].nodeType==3){
       //this javascript engine is counting blank text nodes
       teacherslist=teacherslist.childNodes[4];
       var start=2;
       var step=2;
   }else{
       teacherslist=teacherslist.childNodes[2];
       var start=1;
       step=1;
   }
   function parentseve_toggleonlyselected(state){
       var tmp=teacherslist.childNodes;
       var listlength=teacherslist.childNodes.length;
       if(state){
           for(var i=listlength-start;i>=0;i=i-step){
              if(!tmp[i].childNodes[1].firstChild.firstChild.checked){
                  tmp[i].style.display='none';
              }
           }
       } else {
           for(var i=listlength-start;i>=0;i=i-step){
               tmp[i].style.display='block';
           }
       }
   }
   parentseve_toggleonlyselected(document.getElementsByName('showonlyselected')[0].checked);

</script>

YUI

Using Moodle's default JavaScript library YUI we can overcome those browser inconsistencies. We also move the inline "onclick" event handler to the JavaScript. (Note that the required YUI libraries are already part of a standard Moodle installation.) For attaching the event handler we had to add an ID to the select checkbox.

require_js(array(

       'yui_yahoo',
       'yui_dom-event',
       )

);

<script type="text/javascript">

 // Add the event listener to the checkbox
 var addclick = function(){
   YAHOO.util.Event.addListener('id_showselected', 'click', parentseve_toggleonlyselected);
 };
 // Get a list of all checkboxes
 var teachers = YAHOO.util.Dom.getElementsByClassName('pe_teacher', 'input', 'pe_teachers');
 var parentseve_toggleonlyselected = function() {
   for (var i=0; i < teachers.length; i++){
     // Get a list of the form items for each checkbox
     var formitem = YAHOO.util.Dom.getAncestorByClassName(teachers[i], 'fitem');
     // Hide unchecked teachers if "Show only selected" is checked
     if (YAHOO.util.Dom.get('id_showselected').checked){
       if (!teachers[i].checked){
         formitem.style.display='none';
       }
     } else {
         formitem.style.display='inline';
     };
   };
 };

// Initialise YAHOO.util.Event.onDOMReady(addclick); </script>

jQuery

The jQuery code for the same functionality is significantly shorter. And you get some additional cool effects with the show() function. (Note that the required jQuery library is not part of a standard Moodle installation so you have to provide it yourself.)

require_js(array(

       'jquery/jquery-1.3.2.min.js',
       )

);

<script type="text/javascript">

$(document).ready(function(){

 $("input[name='showonlyselected']").click(function(){
   if(this.checked){
     $('.pe_teacher:not(:checked)').parents('.fitem').hide('normal');
   } else {
     $('.fitem').show('slow');
   };
 });

});

</script>

Advantages:

  • Always working with sets -> inherent looping.
  • Chaining of functions.
  • Provides shorthand (and cross browser) access to native JavaScript functions.

What's left to do?

As this feature will be only available to the user when she has JavaScript activated in her browser we should display the "Show only selected" checkbox also only when JavaScript is available.


Fair comparison

You are asking us to compare the length and understandability of two bits of code, one of which has comments and one which doesn't, and one of which uses anonymous functions an one which doesn't. Allow me to edit the two lots of code to make it a fairer comparison (and also to match the Moodle coding style.--Tim Hunt 03:28, 12 July 2009 (UTC)

YUI

require_js('yui_dom-event');

<script type="text/javascript"> YAHOO.util.Event.onDOMReady(function() {

   YAHOO.util.Event.addListener('id_showselected', 'click', function() {
       var showselected = document.getElementById('id_showselected').checked;
       var teachers = YAHOO.util.Dom.getElementsByClassName('pe_teacher', 'input', 'pe_teachers');
       for (var i=0; i < teachers.length; i++) {
           var formitem = YAHOO.util.Dom.getAncestorByClassName(teachers[i], 'fitem');
           if (showselected && !teachers[i].checked) {
               formitem.style.display='none';
           } else {
               formitem.style.display='inline';
           }
       }
   });

}); </script>

jQuery

require_js('jquery/jquery-1.3.2.min.js');

<script type="text/javascript"> $(document).ready(function() {

   $("input[name = 'showonlyselected']").click(function(){
       if (this.checked) {
           $('.pe_teacher:not(:checked)').parents('.fitem').hide('normal');
       } else {
           $('.fitem').show('slow');
       };
   });

}); </script>

Actually, isn't this buggy? $('.fitem').show('slow'); will show every single .fitem on the whole form, even if they are nothing to do with this show/hide button? What would be very bad if you had two independent show/hide widgets on the same form. --Tim Hunt 03:28, 12 July 2009 (UTC)

You're right, Tim, the show() part is not very precise and would behave like you suggest. But that could easily be amended by defining the context of the form items more precisely, thus restricting the scope to the fieldset at hand: --Frank Ralf 16:15, 20 July 2009 (UTC)
$('#pe_teachers .fitem').show('slow');

A fair comparison - Next round

I take up the gauntlet ;-) Here's the refactored code both for YUI and jQuery.

I created a slightly simpler form for demonstration purposes. Here's the code:

The form

JavaScript1 Teacher list.png

$mform =& $this->_form;

$mform->addElement('checkbox','headmaster', 'Mr. Hunt', 'Headmaster'); $mform->addElement('header', 'teachers', 'Teachers'); $teachers= array('Mr. Smith', 'Ms. Miller', 'Mr. Morgan');

   foreach($teachers as $teacher){
       $mform->addElement(
           'checkbox',
           ,
           $teacher,
           ,                       
           array('class'=>'teacher') 
       );
   };

$mform->closeHeaderBefore('showonlyselected'); $mform->addElement('checkbox','showonlyselected',,'Show only selected teachers');

You see we added another checkbox outside of the fieldset to see whether our code affects any other checkboxes which it shouldn't.

YUI

Actually, I cheated a bit with the first version by giving the checkbox for the "Show only selected" option an ID:

$mform->addElement('checkbox','showonlyselected',,'Show only selected teachers', array('id'=> 'showselected'));

So this is the refactored code which matches the jQuery version more closely:

<script type="text/javascript"> YAHOO.util.Event.onDOMReady(function() {

   var selectbox = document.getElementsByName('showonlyselected')[0];
   YAHOO.util.Event.addListener(selectbox, 'click', function() {
       var teachers = YAHOO.util.Dom.getElementsByClassName('teacher', 'input', 'teachers');
       for (var i=0; i < teachers.length; i++) {
           var formitem = YAHOO.util.Dom.getAncestorByClassName(teachers[i], 'fitem');
           if (selectbox.checked && !teachers[i].checked) {
               formitem.style.display='none';
           } else {
               formitem.style.display='inline';
           }
       }
   });

}); </script>

See also