?
Solved

How does this Javascript work (Part II)?

Posted on 2016-08-04
2
Medium Priority
?
76 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
2 Comments
 
LVL 58

Accepted Solution

by:
Julian Hansen earned 2000 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

Get real performance insights from real users

Key features:
- Total Pages Views and Load times
- Top Pages Viewed and Load Times
- Real Time Site Page Build Performance
- Users’ Browser and Platform Performance
- Geographic User Breakdown
- And more

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In Part 1 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7849-Hex-Maze.html) we covered the hexagonal maze basics -- how the cells are represented in a JavaScript array and how the maze is displayed.  In this part, we'…
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
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…
Suggested Courses

800 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