简体   繁体   English

使用Javascript / jquery如何从所选行的每个单元格中获取值

[英]Using Javascript/jquery how can I get values from each cells in a selected row

I am trying to figure out how to get and assign each cell value in a row to a variable.In particular the check box values 我正在尝试找出如何获取并将行中的每个单元格值分配给变量。特别是复选框值

Here is an example of the table 这是表格的一个例子

<table id="mytable" class="table">
    <thead>
        <b><tr><th>Header1</th><th>Header2</th><th>Header2</th><th>Header3</th></tr></b>
    </thead>
    <tr>
        <td>value1</td>
        <td>value1</td>
        <td>
            <label><input id="divpriority" ng-model="priority" type="checkbox" /> Option1</label>

            <label><input id="divsource" type="checkbox" /> Option2</label>

            <label>  <input type="checkbox" checked/>Otion3</label>
        </td>                   
        <td><br/><br/><button id="buttonvalues" type="button" class="btn-primary">GetValues</button></td>
    </tr>
</table>

So when the "GetValues" button is clicked in the current row the values from each cell are assigned to a variable. 因此,在当前行中单击“ GetValues”按钮时,来自每个单元格的值将分配给一个变量。

I was thinking of something along the lines of this:(I know this is likely incorrect) 我在想一些类似的事情:(我知道这很可能是错误的)

  $("#mytable table tbody ").on("click", "#buttonvalues", function() {
     var header1;
     var header2;
     var Options = new Array()

   var header1 = $(this).closest('tr').header1.val ;
   var header2 = $(this).closest('tr').header2.val

  Options = //Not sure what to do here

Using Javascript/jquery how can I get values from each cells in a selected row and assign the values to a variable with the click of a button included in the row. 使用Javascript / jquery如何从所选行中的每个单元格中获取值,并通过单击行中包含的按钮将值分配给变量。

Please emphasize on assigning the name of the label from the check box into an array variable. 请强调将复选框中的标签名称分配给数组变量。 I would like to get the name of the checkbox thats checked into the array 我想获取已签入数组的复选框的名称

If you want to save off each cell value in the row something like this will work. 如果你想保存行中的每个单元格值,这样的东西就可以了。

Demo Fiddle 演示小提琴

Code: 码:

$("#mytable").on("click", ".btn-primary", function () {
    var values = [];
    var $header = $(this).closest('table').find('thead th');
    var $cols   = $(this).closest('tr').find('td');

    $header.each(function(idx,hdr) {
        var $curCol = $cols.eq(idx);
        var $labels = $curCol.find('label');
        var value;

        if($labels.length) {
            value = {};
            $labels.each(function(lblIdx, lbl) {
                value[$(lbl).text().trim()] = $(lbl).find('input').is(':checked');
            });
        } else {
            value = $curCol.text().trim();
        }
        values.push( { name: $(hdr).text(), value: value } );
    });

    console.log(JSON.stringify(values, null, 2));
});

Result: 结果:

[
  {
    "name": "Header1",
    "value": "value1"
  },
  {
    "name": "Header2",
    "value": "value1"
  },
  {
    "name": "Header3",
    "value": {
      "Option1": false,
      "Option2": false,
      "Option3": true
    }
  },
  {
    "name": "Header4",
    "value": "GetValues"
  }
] 

To get the name of each checked option in an array, change the header loop to: 要获取数组中每个选中选项的名称,请将标题循环更改为:

$header.each(function(idx,hdr) {
    var $curCol = $cols.eq(idx);
    var $labels = $curCol.find('label');
    var value;

    if($labels.length) {
        // Filters for labels containing a checked checkbox
        value = $labels.filter(function(lblIdx) {
            return $(this).find('input').is(':checked');
        }).map(function(valIdx, valLbl) {  // Maps the result to the text value of the label
            return $(valLbl).text().trim();
        }).get();  // returns just the array of values
    } else {
        value = $curCol.text().trim();
    }
    values.push( { name: $(hdr).text(), value: value } );
});

Output Demo Fiddle : 输出演示小提琴

[
  {
    "name": "Header1",
    "value": "value1"
  },
  {
    "name": "Header2",
    "value": "value1"
  },
  {
    "name": "Header3",
    "value": [
      "Option1",
      "Option3"
    ]
  },
  {
    "name": "Header4",
    "value": "GetValues"
  }
] 

I think you're looking to get the values for a row when the row is clicked-on. 我想你在点击行时想要获取一行的值。 If that's the case then your selector could be: $("#mytable").on("click", ".btn-primary", ... . And to get the values of the checkboxes: var priority = $(this).closest('tr').find("input").eq(0).val(); 如果是这种情况,那么您的选择器可以是: $("#mytable").on("click", ".btn-primary", ...并获取复选框的值: var priority = $(this).closest('tr').find("input").eq(0).val();

I'd suggest placing classes on the checkboxes in each row so you can select by that class rather than depending on the HTML structure always being the same an using .eq(0) . 我建议在每行的复选框上放置类,以便您可以通过该类选择,而不是依赖于HTML结构始终使用.eq(0) Your current use of IDs is not specifically valid as they are supposed to be unique in the DOM. 您当前使用的ID并不是特别有效,因为它们在DOM中应该是唯一的。

IDs must be unique, you should use classes instead, assuming you have changed the IDs to classes you can use .map() method which returns an array: ID必须是唯一的,您应该使用类,假设您已将ID更改为可以使用的类.map()方法,它返回一个数组:

$("#mytable").on("click", ".buttonvalues", function() {
     var options = $(this).closest('tr')
                          .find('input[type=checkbox]:checked')
                          .map(function() {
                              return $.trim( $(this).parent().text() );
                          }).get();
});

Please note that $("#mytable table") doesn't select a table that has mytable ID attribute. 请注意, $("#mytable table")不会选择具有mytable ID属性的表。 It selects descendant tables of #mytable element. 它选择#mytable元素的后代表。

Try this: http://jsbin.com/oREJEKo/1/edit 试试这个: http//jsbin.com/oREJEKo/1/edit

$('#mytable').on('click', 'button', function() {
  var checkboxes = $($(this)).closest('tr').find('input[type="checkbox"]');
  var myvalues = [];
  $(checkboxes).each(function() {
    if ( $(this).is(':checked') ) {
       myvalues.push( $(this).closest('label').text() );  
    }
  });

  console.log(myvalues);
});

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

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