简体   繁体   English

JQuery和MVC:Get Row(值)基于CheckBox Selected

[英]JQuery and MVC: Get Row(values) Based on CheckBox Selected

I've got a table with row data. 我有一个包含行数据的表。 Each row has a checkbox that will flag that row for processing. 每行都有一个复选框,用于标记该行以进行处理。 The table is populated with the aid of a DisplayTemplate as can be seen in the below code. 该表由DisplayTemplate填充,如下面的代码所示。 When the user clicks the "Process" button, the code should iterate the table and add all selected rows to an array that will be sent to a web service. 当用户单击“处理”按钮时,代码应迭代表并将所有选定的行添加到将发送到Web服务的数组中。 I thought this would be a simple thing to find an example on, but this hasn't been the case. 我认为找到一个例子是一件简单的事情,但事实并非如此。

This is the table: 这是表:

<table id="hes" class="table-striped table-condensed table-bordered">
        <thead>
            <tr>
                <th></th>
                <th>Detail Id</th>
                <th>Detail Reason Code</th>
                <th>Detail Status Code</th>
            </tr>
        </thead>
        <tbody>
            @if (Model.HesViewModels != null)
            {
                @Html.DisplayFor(i => i.HesViewModels)
            }
        </tbody>

I'm using this JQuery code to get the selected row and can't figure out how to get the row and it's corresponding values into an array. 我正在使用这个JQuery代码来获取所选行,并且无法弄清楚如何将行和它的相应值放入数组中。

$('#process').click(function () {
            var x = $('#hes tr').find('input[type="checkbox"]:checked').each(function () {
               // GET THE VALUES OF THE TDs ON THIS ROW AND STICK IN AN ARRAY
            });
        });

EDIT - Here's what the rendered source looks like for each row: 编辑 - 以下是每行的渲染源的样子:

<tr>
    <td><input data-val="true" data-val-required="The Process field is required." id="HesViewModels_0__Process" name="HesViewModels[0].Process" type="checkbox" value="true" /><input name="HesViewModels[0].Process" type="hidden" value="false" /></td>
    <td>500116</td>
    <td>0</td>
    <td>1</td>
</tr>
$(function(){

  $("#process").click(function(e){
     e.preventDefault();

      var idArray=[]; 

     $("#hes").find('input[type="checkbox"]:checked').each(function (i,k) {

         var item =$(this);       

         //Read the Id of the selected checkbox item.

         idArray.push(item.attr("id"));

     }); 
     console.log(idArray);
     //idArray is an array which has the Id of the checked checkboxes
     //now you can send the idArray to your web service endpoint

  });

});

If you want to get any other attribute value other than the id , you may replace id the expression item.attr("id") with your custom attribute name. 如果要获取除id之外的任何其他属性值,可以使用自定义属性名称将表达式item.attr("id")替换为id。

Here is a working jsbin sample. 是一个有效的jsbin样本。


Edit : As per the comments, you want to send more data. 编辑:根据评论,您希望发送更多数据。 It is not a good idea to send the markup of html row as it is(like you mentioned in the comment). 发送html行的标记不是一个好主意(就像你在评论中提到的那样)。 It is best to get the required data you want and send it in format which the web service can easily understand. 最好获得所需的数据,并以Web服务可以轻松理解的格式发送。 Having a web service end point which accepts the HTML string and parse it for some data is a bad idea ! 拥有一个接受HTML字符串并为某些数据解析它的Web服务端点是个坏主意!

So i suggest you to keep the data you want to send, in HTML 5 data attributes. 因此,我建议您在HTML 5数据属性中保留要发送的数据。 You may update your razor code like 您可以更新您的剃刀代码

<tbody>
@if (Model.HesViewModels != null)
{
    foreach (var item in Model.HesViewModels)
    {
        <tr>
            <td>
                @Html.CheckBoxFor(s => item.Process, 
                                  new {data_detailid = item.DetailId,
                                       data_reasoncode = item.DetailRasonCode})
            </td>
            <td>@item.DetailId</td>
            <td>@item.DetailRasonCode</td>
        </tr>
    }
}
</tbody>

This will render the check box items with 2 data attributes, detailid and reasoncode 这将使复选框项目具有2个数据属性, detailidreasoncode

So in our jQuery code, We just need to read the data attribute values of the selected checkboxes. 所以在我们的jQuery代码中,我们只需要读取所选复选框的数据属性值。

$(function () {

    $("#yourProcessBtnId").click(function (e) {
        e.preventDefault();

        var itemsArray = [];     
        $("#hes").find('input[type="checkbox"]:checked').each(function (i, k) {

          var item = $(this);                     
          var row = { detailId:item.data("detailid"), reasonCode: item.data("reasoncode")} 
          itemsArray.push(row);

        });
        //you can send itemsArray now.
        console.log(itemsArray);

    });
});

itemsArray will be an array of object with properties detailId and reasonCode itemsArray将是一个对象数组,其属性为detailIdreasonCode

You're iterating through the checkboxes so you could use the .parents() function, (between your .find() and .each(), https://api.jquery.com/parents/ ) to select the containing trs and then iterate through them. 您正在遍历复选框,以便您可以使用.parents()函数(在.find()和.each(), https: //api.jquery.com/parents/之间)来选择包含的trs和然后迭代它们。 Something like: 就像是:

$('#process').click(function () {

    $('#hes tr').find('input[type="checkbox"]:checked').parent('tr').each(function () {
    // GET THE VALUES OF THE TDs ON THIS ROW AND STICK IN AN ARRAY
    });
});

Alternatively, you could do something like this: 或者,您可以这样做:

$('#process').click(function () {
    $('#hes tbody tr').each(function () {
        var $self = $(this);
        if ($self.find(':checkbox').is(':checked'))
        {
            // Here you must look for values within the row (give your tds different ids, or class names to be able to select them 

            var someValue = $self.find('td.someValue').text();
            // use the value to stick it into the array

        }
    });
});

You can stick the values into the array like in @Shyju's answer. 您可以像@ Shyju的回答一样将值粘贴到数组中。

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

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