简体   繁体   English

如何使用全选/取消全选在基于分页的表中实现多个复选框,然后将所有选定的复选框 IDS 存储到 localstoarge

[英]How to implement Multiple Checkbox in a pagination based table with Check/Uncheck All and then store all selected checkbox IDS into localstoarge

I am not JavaScript expert.我不是 JavaScript 专家。 I am trying to implement some features in my table where I have a list of patients.我正在尝试在我有患者列表的表中实现一些功能。 I tried many ways, but can't be able to implement all features together from different approaches.我尝试了很多方法,但无法通过不同的方法一起实现所有功能。 What I am trying to do in my table is:我想在我的桌子上做的是:

  • Check/Uncheck Patients.选中/取消选中患者。
  • Check/Uncheck all should work on all paginated pages.选中/取消选中所有应该适用于所有分页页面。
  • Store selected patients IDs into local storage.将选定的患者 ID 存储到本地存储中。
  • Whenever clicking on Check/Uncheck checkbox and individual checkbox, it should update & save the updated selected patient IDs into local storage.每当单击选中/取消选中复选框和单个复选框时,它应该更新并将更新后的选定患者 ID 保存到本地存储中。
  • At the end, I just need the local storage Key.最后,我只需要本地存储密钥。 contains all selected patient IDs.包含所有选定的患者 ID。

Here is the image of the patient table.这是患者表的图像。

HTML HTML

<div class="table-responsive">
  <table class="table" id="table">
    <thead>
      <tr class="text-muted">
        <th scope="col">
          <!---------------- Check / Uncheck All Checkboxes ----------->
            <input type="checkbox">
          <!----------------/ Check / Uncheck All Checkboxes ----------->
          <span class="d-none d-md-inline d-lg-inline select_counter"></span>
        </th>
        <th class="col-2">Patient</th>
        <th class="col-1">Age</th>
        <th class="col-1">Gender</th>
        <th class="col-1">Diagnosis</th>
        <th class="col-1">Medication</th>
        <th class="col-1">Last Rx</th>
      </tr>
    </thead>
    <tbody>
      <% @list_users.each.with_index(1) do |patient, index| %>
        <tr>

          <td class="col-1">
          <!---------------- Checkbox To Select Each Patient ------------->
             <input type="checkbox" id="<%= patient.id %>">
          <!---------------/ Checkbox To Select Each Patient ------------->
          </td>

          <td>
          <%=link_to user_name(patient.id)&.strip&.upcase, centres_ebroadcasts_find_by_id_path(user_id: patient.id,source:'patient_table'), :class=>"text-dark", remote:true %>
          </td>
          <td><%= patient&.date_of_birth? ? Date.today.year - patient&.date_of_birth.year : " -- " %></td>
          <td><%= patient.gender? ? patient.gender : "--" %></td>
          <td class="col-2">
            <% diagnosis = patient.consultations.map(&:diagnosis)%>
              <% if diagnosis.compact.empty? %>
                <span class="text-danger">No Diagnosis</span>
              <% else %>
                <%= truncate_text(diagnosis.uniq.compact.join(", "),120).upcase %>
            <% end %>
          </td>
          <td class="col-2">
            <% if medicine = patient&.prescriptions&.completed_prescriptions.map(&:medicines).empty? %>
              <span class="text-danger">No Medicines</span>
            <% else %>
              <%= truncate_text(patient&.prescriptions&.completed_prescriptions.map(&:medicines).flatten.map(&:name).uniq.compact.join(", "), 120).upcase %>
            <% end %>
          </td>
          <td class="col-2"><%= patient&.prescriptions&.completed_prescriptions&.first&.created_at&.strftime("%d, %B, %Y")%></td>
        </tr>
      <% end %>
    </tbody>
  </table>
</div>

<!--------------- Patient List Paginator -------------->
  <%= paginate @list_users %>
<!--------------/ Patient List Paginator -------------->

<!----------- Javascript --------->
<script>
</script>
<!----------/ Javascript --------->

Issues: When I was trying different approaches, I faced several issues in pagination.问题:当我尝试不同的方法时,我遇到了几个分页问题。 For example: checkboxes are only working on current paginated page.例如:复选框仅适用于当前分页页面。 Check/Uncheck only works on current paginated page.选中/取消选中仅适用于当前分页页面。

Could anyone please help me to implement this?谁能帮我实现这个? Pure JavaScript or jQuery, any can be used.纯JavaScript或jQuery,任意一个都可以。

Let's say that you are storing the IDs in your localstorage, by doing something like this.假设您通过执行以下操作将 ID 存储在本地存储中。 Also, since you mentioned that a jQuery solution would work for you, I'll show you how to do it in jQuery.此外,由于您提到 jQuery 解决方案对您有用,我将在 jQuery 中向您展示如何进行。

Also, a few inital assumptions:此外,还有一些初步假设:

  • the IDs are unique. ID 是唯一的。 There can be no two (or more) patients with the same ID不能有两个(或更多)具有相同 ID 的患者
  • the IDs are numerical. ID 是数字。 This was done purely for simplification's sake这样做纯粹是为了简化

Resources used:使用的资源:

  • uniques is a filtering function intially posted in this SO answer . uniques是一个过滤 function 最初发布在这个 SO answer中。 I'm using it here, because it fits the purpose (removing (numerical) duplicates from a one-dimensional array), before writing to localstorage我在这里使用它,因为它符合目的(从一维数组中删除(数字)重复项),然后再写入本地存储
  • removeItemAll is used to remove eventual multiple occurrences of an ID. removeItemAll用于删除最终多次出现的 ID。 The function was initiallly posted in this SO answer function 最初发布在此 SO 答案

Final notes:最后说明:

  • the code below has not been tested, but it should work下面的代码没有经过测试,但它应该可以工作
  • you would need to implement automatic checking of freshly loaded patients, if their ID is found in localstorage.如果在本地存储中找到他们的 ID,您将需要对新加载的患者实施自动检查。 That bit is not included in the code below该位不包含在下面的代码中
// helper functions
function uniques(value, index, self) {
    return self.indexOf(value) === index;
}

function removeItemAll(arr, value) {
    var i = 0;
    while (i < arr.length) {
        if (arr[i] === value) {
            arr.splice(i, 1);
        } else {
            ++i;
        }
    }
    return arr;
}

var idsToStore; // we'll use this later on

// let's take whatever we have in localstorage
// I'm going to use a JSON to store the IDS, and
// that JSON has this structure:
// {"ids" : [1,1,2,3,5,8,13....]}

// the IDs are stored in localstorage with the
// key of patientIDs
var stored = localStorage.getItem("patientIDs");
if(stored) {
    stored = JSON.parse(stored);
    stored = stored.ids; // this will give us an array to work with
} else {
    stored = []; // nothing was stored before
}

// let's get the ids of the checked patients
// this event handler is attached with the
// assumption that your table is always on the page
// and is not being CREATED dynamically (just filled
// dynamically). I'm also going with the
// assumption that your patient checkboxes have a 
// class called patients, and that your table
// has an ID of myTable

$("#myTable input[type=checkbox].patients").on("change",function(e) {
    e.preventDefault();

    // we note the id
    idsToStore = $(this).data("id");

    // we check the checkbox state
    if($(this).is(":checked")) {
        // if it's checked, we add it, if it's not already there
        if(stored.indexOf(idsToStore) <0) {
            stored.push(idsToStore);
        }

    // if the checkbox is no longer checked...
    } else {
        // ... remove it, if it was in the array
        const index = array.indexOf(idsToStore);
        if (index > -1) {
            // ... remove all occurrences, just in case there
            // were ever more than one
            removeItemAll(stored,idsToStore);
        }
    }

    // after everything's done, let's write back
    // to localstorage. To keep it in a JSON-like
    // format, I'm using JSON.stringify
    localStorage.setItem('patientIDs',JSON.stringify(stored));
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM