简体   繁体   English

将选中复选框的表行提取到对象数组中

[英]Extract table rows having checked checkboxes into array of objects

I'm trying to save the specific objects in an array that has the checkbox 'checked'.我正在尝试将特定对象保存在一个“选中”复选框的数组中。 I want to create the new array so I can use only those latter.我想创建新数组,所以我只能使用后者。

How can I do that using jquery?我如何使用 jquery 做到这一点?

'use strict';

class event {
  constructor(jQuery) {
    this.$ = jQuery;
  }

  getEvents(eventKey) {
    let aEvents = [{
        eventName: 'ABDCCC',
        // true = checked
        status: true
      },
      {
        eventName: 'ACC',
        status: true
      }
    ];
    return aEvents;

    /**
     * Update
     * @param {array} [aEvents]
     */
    setEvents = function(aEvents) {
      // Put them on a table
      var table = this.$('#eventsTable');
      table.find('tbody tr').remove();
      for (var i = 0; i < aEvents.length; i++) {
        let event = aEvents[i];
        table.find('tbody').append(`
        <tr>
          <td>
            ${event.eventName}
          </td>
          <td>
          <div id="check-list" class="custom-control custom-switch">
            <input type="checkbox" class="custom-control-input" ${event.status ? 'checked' : ''} id="customSwitch${i}"/>
            <label class="custom-control-label" for="customSwitch${i}"></label>
          </div>
          </td>
        </tr>
      `);
      }
    }
  }

I want to get this result我想得到这个结果

  • You can check the Events you like (done)您可以查看您喜欢的活动(完成)
  • When click on a button ('save this events' for ex) only the checked events will be saved on a new array of objects, the same ones in getEvents()单击按钮时(例如“保存此事件”),只有选中的事件将保存在新的对象数组中,与 getEvents() 中的对象数组相同

Conventionally, you would need to pass some anchor to your desired property name within <td> HTML-attributes (say, it would be prop attribute).按照惯例,您需要在<td> HTML 属性中将一些锚点传递给所需的属性名称(例如,它是prop属性)。 If you don't want property names to be hardcoded (which is not so flexible).如果您不希望对属性名称进行硬编码(这不太灵活)。

Next, you simply need to select <tr> nodes having ( .has("input:checked") ) checked checkbox.接下来,您只需选择具有 ( .has("input:checked") ) 复选框的<tr>节点。

With that you iterate over selected rows, turning first ( :lt() ) <td> nodes, containing your target data into object properties:有了它,您可以遍历选定的行,首先将 ( :lt() ) <td>节点包含目标数据转换为对象属性:

 $('#savebtn').on('click', () => { const selectedRows = [...$('table tbody tr:has("input:checked")')] .map(tr => [...$(tr).find('td:lt(2)')] .reduce((res,td) => (res[$(td).attr('prop')]=$(td).text(), res),{})) console.log(selectedRows) })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <thead> <tr> <th>Event name</th><th>Visitors qty</th><th>visited</th> </tr> </thead> <tbody> <tr> <td prop="eventname">Christmass Eve Party</td><td prop="qty">500</td><td><input type="checkbox"></input> </tr> <tr> <td prop="eventname">Thanksgivin Day</td><td prop="qty">300</td><td><input type="checkbox"></input> </tr> <tr> <td prop="eventname">Independence Day</td><td prop="qty">600</td><td><input type="checkbox"></input> </tr> </tbody> </table> <button id="savebtn">Save</button>

Here is a very simple way to perform what you want:这是执行您想要的操作的一种非常简单的方法:

 var arr = []; $("#ok").click(function(){ $("#results").html(""); arr = []; $('input.events[type="checkbox"]').each(function(){ if($(this).is(":checked")){ var evName = $(this).attr("id"); arr.push($('label[for="'+evName+'"]').text()); $("#results").append("<p>"+$('label[for="'+evName+'"]').text()+"</p>"); } }); });
 table{ width:100%; } table td{ display:block; } #results p{ display:block; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tbody> <tr> <td><input type="checkbox" class="events" id="ev1" /> <label for="ev1">Event One</label> </td> <td><input type="checkbox" class="events" id="ev2" /> <label for="ev2">Event Two</label> </td> <td><input type="checkbox" class="events" id="ev3" /> <label for="ev3">Event Three</label> </td> <td><input type="checkbox" class="events" id="ev4" /> <label for="ev4">Event Four</label> </td> <td><input type="checkbox" class="events" id="ev5" /> <label for="ev5">Event Five</label> </td> <td> <button id="ok">OK</button> </td> </tr> </tbody> </table> <h5>Selected events :</h5> <div id="results"></div>

Here's a solution:这是一个解决方案:

let checkedEvents = [];
$('#eventsTable').find('tbody tr').each(function(index) {
  if( $(this).find("input[type='checkbox'][id^=customSwitch]").prop('checked') ) {
    checkedEvents.push({
      eventName: $(this).find("td:first-child").text().trim(),
      status: $(this).find("input[type='checkbox'][id^=customSwitch]").prop('checked'),
    });
  }
});
// Do something with checkedEvents

If you are going to do this with more labels/table cells in a row, adding an id, class or other property to them might be helpful for targetting.如果您要连续使用更多标签/表格单元格来执行此操作,向它们添加 id、类或其他属性可能有助于定位。 If you do this consequently, you could even use a loop to set all attributes of the object.如果您因此这样做,您甚至可以使用循环来设置对象的所有属性。

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

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