• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 84
  • Last Modified:

How does this Javascript work (Part II)?

Here's my code:

define(['/assets/js/views/app2/custom_checkbox_and_radio.js','jquery'],function(){
    return function(){
      $('.at_filters label').click(function(){
        $(this).siblings('.checkbox').click();
      });
      $('input[name="filt"]').on('change',function(){
        if(this.value=='all'){
          if($(this).is(':checked')) $('input[name="filt"]').attr('checked', true);
          else $('input[name="filt"]').attr('checked', false);
        } else {
          $('input[name="filt"][value="all"]').attr('checked', false);
        }
        var show = [];
        var left = true;
        $('input[name="filt"]:checked').each(function(){
          show.push($(this).val());
        });
        var year = '';
        var month = '';
        $('.at_timeline_list li').each(function(){
          if($(this).hasClass('yearheader')){
            if(year && year.data('delete')) year.slideUp();
            else if(year) year.slideDown();
            year = $(this);
            year.data('delete', true);
          } else if($(this).hasClass('monthheader')){
            if(month && month.data('delete')) month.slideUp();
            else if(month) month.slideDown();
            month = $(this);
            month.data('delete', true);
          } else if($(this).hasClass('event')){
            if(show.indexOf($(this).data('type'))!=-1){
              $(this).removeClass('left').removeClass('right');
              $(this).addClass(left?'left':'right');
              left=!left;
              if($(this).css('display')!='list-item') $(this).slideDown();
              year.data('delete',false);
              month.data('delete',false);
            } else {
              if($(this).css('display')=='list-item') $(this).slideUp();
            }
          }
        });
        if(year && year.data('delete')) year.slideUp();
        else if(year) year.slideDown();
        if(month && month.data('delete')) month.slideUp();
        else if(month) month.slideDown();
      });

      //Account Search
      $('input.at_search').keypress(function(e){
        if(e.which == 13){
          $(this).siblings('.magnificon').click();
        }
      });
      $('.at_searchwrap .magnificon').click(function(){
        if(!$('.at_search').val()) return;
        pf.ajax({
          url:'/app/accounttimeline',
          data:{searchfor:$('.at_search').val()},
          type:'post',
          dataType:'json',
          success:function(res){
            if(res.success && res.body){
              if(res.loadAccount){
                pf.apps.loadApp({
                  appurl:'/app/accounttimeline',
                  postdata:{accountkey:res.loadAccount},
                  refresh:new Date()
                });
              } else pf.dialog(res.body, 'Search Results');
            } else {
              pf.dialog('There has been an issue processing your request. I apologize for the inconvenience, please try again.', 'Error');
            }
          }
        });
      });

      setupLabel();
    };
});

Open in new window


I'm breaking it down in pieces. Thus far, we've defined a series of buttons and coupled some functionality to those buttons which includes a collection of functions. The first one is immediately after the "return function" code at line 6...

Lines 3-5 are a clunky way of associating a function with the "label" span, and then we're stating that all checkboxes that are associated with the label span are triggering the function that begins on line 6.

This first part:

$('input[name="filt"]').on('change',function(){
        if(this.value=='all'){
          if($(this).is(':checked')) $('input[name="filt"]').attr('checked', true);
          else $('input[name="filt"]').attr('checked', false);
        } else {
          $('input[name="filt"][value="all"]').attr('checked', false);
        }

Open in new window


...is saying that if any of the checkboxes named "filt" (which is all of them) have a value of "all," then all of the checkboxes are to be checked.

Here's the HTML code for that part of the page:

 <ul class="at_filters">
      <li>
        <span class="checkbox">
          <input type="checkbox" name="filt" value="all" checked/>
        </span><label>All</label>
      </li>
      <li>
        <span class="checkbox">
          <input type="checkbox" name="filt" value="transaction" checked/>
        </span><label>Transactions</label>
      </li>
      <li>
        <span class="checkbox">
          <input type="checkbox" name="filt" value="statement" checked/>
        </span><label>Statements</label>
      </li>
      <li>
        <span class="checkbox">
          <input type="checkbox" name="filt" value="note" checked/>
        </span><label>Notes</label>
      </li>
      <li>
        <span class="checkbox">
          <input type="checkbox" name="filt" value="comment" checked/>
        </span><label>Task Comments</label>
      </li>
	  <li>
        <span class="checkbox">
          <input type="checkbox" name="filt" value="personal_payments" checked/>
        </span><label>Personal Payments</label>
      </li>
    </ul>

Open in new window


Now, this part of the code is where I'm getting fuzzy:

 var show = [];
        var left = true;
        $('input[name="filt"]:checked').each(function(){
          show.push($(this).val());
        });
        var year = '';
        var month = '';

We establish two variables, which I'm thinking will coincide with the CSS attributes that are attached to the different "<li>'s." But can you break it down for me?

I see the "filt," and I'm assuming that when one of the "filts" is checked (based on the "onchange" dynamic mentioned earlier), then the value associated with that checkbox (all, transaction, statement, notes, etc) is "pushed," right?

What is "show.push?"
0
brucegust
Asked:
brucegust
1 Solution
 
Julian HansenCommented:
The first one is immediately after the "return function" code at line 6...
Just to clarify the return function encapsulates all the code up to line 81.

show.push is just adding the values from the filt checkboxes to an array.

show is defined as an array (show = []) and push is just adding an item to the array.

The code is dynamically establishing what values of checkboxes are on the page.

Hint: you might find it easier to work with if you reformat the code - here is a sample in case it is useful
<script>
define(['/assets/js/views/app2/custom_checkbox_and_radio.js','jquery'],function(){
  return function(){
      // Initialisation code here
      var show = [];
      var left = true;
      $('input[name="filt"]:checked').each(function(){
        show.push($(this).val());
      });
      
      var year = '';
      var month = '';
      
      $('.at_timeline_list li').each(function(){
        if($(this).hasClass('yearheader')){
          if(year && year.data('delete')) {
            year.slideUp();
          }
          else if(year) {
            year.slideDown();
          }
          year = $(this);
          year.data('delete', true);
        }
        else if($(this).hasClass('monthheader')){
          if(month && month.data('delete')) {
            month.slideUp();
          }
          else if(month) {
            month.slideDown();
          }
          month = $(this);
          month.data('delete', true);
        } 
        else if($(this).hasClass('event')) {
          if(show.indexOf($(this).data('type'))!=-1) {
            $(this).removeClass('left').removeClass('right');
            $(this).addClass(left?'left':'right');
            left=!left;
            if($(this).css('display')!='list-item') {
              $(this).slideDown();
            }
            year.data('delete',false);
            month.data('delete',false);
          }
          else {
            if($(this).css('display')=='list-item') {
              $(this).slideUp();
            }
          }
        }
      });
      
      if(year && year.data('delete')) {
        year.slideUp();
      }
      else if(year) {
        year.slideDown();
      }
      if(month && month.data('delete')) {
        month.slideUp();
      }
      else if(month) {
        month.slideDown();
      }
    });

    setupLabel();
	
    // Event Handlers
    $('.at_filters label').click(function(){
      $(this).siblings('.checkbox').click();
    });
	
    $('input[name="filt"]').on('change',function(){
      if(this.value=='all'){
        if($(this).is(':checked')) {
          $('input[name="filt"]').attr('checked', true);
        }
        else {
          $('input[name="filt"]').attr('checked', false);
        }
      } 
      else {
        $('input[name="filt"][value="all"]').attr('checked', false);
      }
	  
    //Account Search
    $('input.at_search').keypress(function(e){
      if(e.which == 13){
        $(this).siblings('.magnificon').click();
      }
    });
    
    $('.at_searchwrap .magnificon').click(function(){
      if(!$('.at_search').val()) return;
      pf.ajax({
        url:'/app/accounttimeline',
        data:{searchfor:$('.at_search').val()},
        type:'post',
        dataType:'json',
        success:function(res) {
          if(res.success && res.body) {
            if(res.loadAccount) {
              pf.apps.loadApp({
                appurl:'/app/accounttimeline',
                postdata:{accountkey:res.loadAccount},
                refresh:new Date()
              });
            } 
            else {
              pf.dialog(res.body, 'Search Results');
            }
          } 
          else {
            pf.dialog('There has been an issue processing your request. I apologize for the inconvenience, please try again.', 'Error');
          }
        }
      });
    });
  };
});
</script>

Open in new window

Sometimes badly formatted code can confuse you.
It is also a good idea to separate the event handlers from the intialisation code  - the above code mixes it all up - event handlers at the top and the bottom - rather move the handlers all to the bottom and keep the init code together.

Also comment as you go so that you can see what each section is doing.
0
 
brucegustAuthor Commented:
Excellent, Julian! Thank you!

One, perhaps two more inquiries, and I think my workplace will be handing me my cape and superhero soundtrack. Here's the next question: https://www.experts-exchange.com/questions/28961753/What-part-of-this-Javascript-dictates-the-visibility-of-the-li-values.html
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now