Solved

How does this Javascript work (Part II)?

Posted on 2016-08-04
2
37 Views
Last Modified: 2016-08-05
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
Comment
Question by:brucegust
2 Comments
 
LVL 51

Accepted Solution

by:
Julian Hansen earned 500 total points
ID: 41743192
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
 

Author Comment

by:brucegust
ID: 41744314
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

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

This article shows how to create and access 2-dimensional arrays in JavaScript.  It includes a tutorial in case you are just trying to "get your head wrapped around" the concept and we'll also look at some useful tips for more advanced programmers. …
When you need to keep track of a simple list of numbers or strings, the Array object is your most direct tool.  As we saw in my earlier EE Article (http://www.experts-exchange.com/A_3488.html), typical array handling might look like this: (CODE) B…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now