toggle font awesome not working

I'm trying to get a fontawesome icon to toggle when a column is hidden. Ironically it works when I alert a string but the alert happens twice and on the second alert the icon toggles back to its original state. I'm not too worried about the alert because it won't we there. But I thought it was strange. Here is what I have...

The HTML

    <div id="user-options">
        <p><label class="links"><input type="checkbox" class="hidden" name="col_1" checked="checked" /><i class="fa fa-toggle-on"></i> First Name</label></p>
        <p><label class="links"><input type="checkbox" class="hidden"  name="col_2" /><i class="fa fa-toggle-off"></i> Last Name</label></p>
        <p><label class="links"><input type="checkbox" class="hidden"  name="col_3" checked="checked" /><i class="fa fa-toggle-on"></i> Email</label></p>
    </div>

    <table id="report">
        <thead>
           <tr>
              <th class="col_1">First Name</th>
              <th class="col_2">Last Name</th>
              <th class="col_3">Email</th>
           </tr>
        </thead>
        <tbody>
           <tr>
              <td class="col_1">Kevin</td>
              <td class="col_2">Smith</td>
              <td class="col_3">[email protected]</td>
           </tr>
           <tr>
              <td class="col_1">Jim</td>
              <td class="col_2">James</td>
              <td class="col_3">[email protected]</td>
           </tr>
        </tbody>
     </table>

And The Javascript

    $("input:checkbox:not(:checked)").each(function() {
         var column = "#report ." + $(this).attr("name");
         $(column).hide();
      });
    $("input:checkbox").click(function(){
         var column = "#report ." + $(this).attr("name");
         $(column).toggle();
      });


    $('label.links').click(function(){
    $(this).find('i.fa').toggleClass('fa-toggle-on fa-toggle-off');
    });

Toggling the columns works fine but toggling the icons does not. I have tried to put the toggle class inside the click function of the checkboxes. Thanks for any help anyone can give me. I have been working on this all day and am getting nowhere.

Answers 1

  • Please check this working demo: JSFiddle.

    Just put the icon toggling code in the input click event:

    $("input:checkbox").click(function() {
      var column = "#report ." + $(this).attr("name");
      $(this).next('i.fa').toggleClass('fa-toggle-on fa-toggle-off');
      $(column).toggle();
    });
    

    ==========================

    UPDATE:

    If you stick to your original solution, check this: JSFiddle.

    Your code doesn't work because the click event is captured and propagated twice. Just stop the propagation:

    $("input:checkbox").click(function(e) {
      var column = "#report ." + $(this).attr("name");
      $(column).toggle();
      e.stopPropagation();
    });
    

Related Articles