Warm tip: This article is reproduced from serverfault.com, please click

When click on button, show divs with checked checkbox using JQuery

发布于 2020-12-04 15:52:46

I want to use JQuery on my Coldfusion application for showing/hiding div elements with checkbox checked/unchecked within the div.

Basically, in a view I show multiple divs elements, every div have also more divs inside, one of these internal divs contains an input type checkbox that could come checked or unchecked.

I also have three buttons in that view 'Active, Inactive, All'. When clicking on Active I want to show all div elements with checkbox checked, not showing the unchecked, and the other way around when clicking on Inactive.

<div class="btn-group ">
  <button id="actives" type="button">Actives</button>
  <button id="inactives" type="button">Inactives</button>
  <button id="all" type="button">All</button>
</div>

<div id="apiDiv">
  <cfloop array="#apis#" index="api">
    <div class="card card-found">
      <div class="card-header">
        <cfif Len(api.iconClass)>
          <i class="fa fa-fw #api.iconClass#"></i>
        </cfif>
        #structKeyExists( api, "name" ) ? api.name : api.id#
      </div>
      <div class="card-body">
        <p>#api.description#</p>
      </div>
      <div class="card-button">
        <input class="#inputClass# ace ace-switch ace-switch-3" name="#inputName#" id="#inputId#-#api.id#" type="checkbox"  value="#HtmlEditFormat( api.id )#"<cfif ListFindNoCase( value, api.id )> checked="checked"</cfif> tabindex="#getNextTabIndex()#">
        <span class="lbl"></span>
      </div>
    </div>
  </cfloop>
</div>

I´m not an expert at all with JQuery. The only thing I have done is what follows and I do not know whether if is a good beggining or not:

$("#actives").click(function (e) {
  $("#apiDiv .card").filter(function() {
    <!--- code here --->
  });
});

Someone please that can help me with it? Thanks a lot in advance!

Questioner
Pablo Portillo
Viewed
0
user12031119 2020-12-05 02:38:09

After your CF code executes, it will generate a .card for each loop iteration of your apis array. So you jQuery code will need a click handler for the #actives button and that will loop through each() iteration of the checkboxes to determine the checked/unchecked state. At that point find the closest() ancestor .card and show()/hide() the .card depending upon the checkbox state.

$("#actives").click(function (e) {
    $('input[type=checkbox]').each(function() {
        if (this.checked) {
            $(this).closest(".card").show();
        } else {
            $(this).closest(".card").hide();
        }
    });
});