Search code examples
javascriptjqueryslim-langruby-on-rails-4.2

OnClick event not binding/firing


I'm trying to create a select link that fire all checkbox on the current page but it doesn't work just reloads the page.

file_items.js

$('a.select-all-current').click(function(e){
  e.preventDefault();
  alert(e);
  $('input:not(:checked)').each(function(index, element){
    $(element).click();
  });
  return false;
});

index.html.slim

...
.col-lg-6.pull-right.align-right
      .pull-right
        = link_to 'Deselect All', '#', class: 'label'
      .dropdown.col-lg-2.pull-right
        a#selectAllMenu.dropdown-toggle[ data-toggle='dropdown' aria-expanded='true']
          .label.select-all
            = "Select All  "
            span.caret.pull-right
        ul.dropdown-menu[role='menu'  aria-labelledby='selectAllMenu']
          li 
            | SELECT
          li
            hr
          li
            = link_to 'current page', '', class: 'select-all-current'
          li
            = link_to 'all files', '', class: 'select-all-files'
          li
            = link_to 'all untagged files', '', class: 'select-all-untagged'
...

Solution

  • You need to wrap the code in a document ready statement like this.

    $(function() { 
        $('a.select-all-current').click(function(e){
          e.preventDefault();
          alert(e);
          $('input:not(:checked)').each(function(index, element){
            $(element).click();
          });
          return false;
        });
    });