5

I have a simple table as following which has checkboxes in the first and last columns of each row.

<table style="width:100%">
  <tr>
    <td><input type="checkbox" /></td>
    <td>Smith</td> 
    <td><input type="checkbox" /></td>
  </tr>
  <tr>
    <td><input type="checkbox" /></td>
    <td>Jackson</td> 
    <td><input type="checkbox" /></td>
  </tr>
</table>

Problem: When I check/uncheck the last column's checkbox in the first row, the first column's checkbox in the same row should be checked/unchecked. Similarly, if I check/uncheck the first column's checkbox, the corresponding last column checkbox should be checked/unchecked.

How can I achieve this in javascript? Any help or pointers would be really appreciated.

Here is the fiddle which I have created: Fiddle

Thank you.

ShellZero
  • 4,415
  • 12
  • 38
  • 56
  • @RayonDabre I wanted to do it in JavaScript. But sure, jQuery should be great. – ShellZero Mar 28 '16 at 17:03
  • 1
    You may take a look at this Javascript solution and modify the Row's onClick event per your purpose: http://www.codeproject.com/Tips/209416/Click-select-row-in-ASP-NET-GridView-or-HTML-Table – Alexander Bell Mar 28 '16 at 17:09

2 Answers2

6

Use :checkbox selector to select input type checkbox elements.

Try this:

$(':checkbox').on('change', function() {
  $(this).closest('tr').find(':checkbox').prop('checked', this.checked);
});
table,
th,
td {
  border: 1px solid black;
  border-collapse: collapse;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<table style="width:100%">
  <tr>
    <td>
      <input type="checkbox" />
    </td>
    <td>Smith</td>
    <td>
      <input type="checkbox" />
    </td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" />
    </td>
    <td>Jackson</td>
    <td>
      <input type="checkbox" />
    </td>
  </tr>
</table>

Using JavaScript:

Use querySelectorAll('[type="checkbox"]') to find checkbox elements.

Try this:

var checkboxes = document.querySelectorAll('[type="checkbox"]');
[].forEach.call(checkboxes, function(checkbox) {
  checkbox.onchange = function() {
    var currentRow = this.parentNode.parentNode;
    var cbElems = currentRow.querySelectorAll('[type="checkbox"]');
    [].forEach.call(cbElems, function(cb) {
      cb.checked = this.checked;
    }.bind(this))
  };
});
table,
th,
td {
  border: 1px solid black;
  border-collapse: collapse;
}
<table style="width:100%">
  <tr>
    <td>
      <input type="checkbox" />
    </td>
    <td>Smith</td>
    <td>
      <input type="checkbox" />
    </td>
  </tr>
  <tr>
    <td>
      <input type="checkbox" />
    </td>
    <td>Jackson</td>
    <td>
      <input type="checkbox" />
    </td>
  </tr>
</table>
Rayon
  • 36,219
  • 4
  • 49
  • 76
  • Awesome. I didn't think of the closest at all! That was a fantastic answer! Thanks a lot! I was wondering how I could do it in JavaScript! Any pointers for that? – ShellZero Mar 28 '16 at 17:13
  • Wow. Thanks a lot @RayonDabre – ShellZero Mar 28 '16 at 17:25
  • Instead of passing the ":checkbox" or type="checkbox", can we give an id to the input type and achieve the same? I tried it out, it didn't work though! – ShellZero Mar 28 '16 at 17:29
  • When you talk about `id`, they must be unique.. And that is the reason one should not go with `ids` when dealing with `n` number of elements of same kind.. __Yes__, It is possible but why do you really need it ? – Rayon Mar 28 '16 at 17:31
  • True. Sorry not the id, a "class". Just curious. Nothing else :) – ShellZero Mar 28 '16 at 17:36
  • 1
    Yes..You can deal with `classes` – Rayon Mar 28 '16 at 17:37
  • `'input[type="checkbox"].myclass'` would select those with that class; pretty much the same answer I was typing otherwise. – Mark Schultheiss Mar 28 '16 at 19:02
1

One possible Javascript solution to toggle Checkboxes on Table Row click is shown below:

HTML

<table id = "Table1">
  <tr>
    <td><input type="checkbox" /></td>
    <td>John Smith</td> 
    <td><input type="checkbox" /></td>
  </tr>
  <tr>
    <td><input type="checkbox" /></td>
    <td>Anna Warner</td> 
    <td><input type="checkbox" /></td>
  </tr>
</table>

CSS

table, th, td{
  border: 1px solid #c0c0c0;
  border-collapse: collapse;
}
table{width:100%;}

Javascript

   // row click will toggle checkboxes
   row_OnClick("Table1")
   function row_OnClick(tblId) {
    try {
        var rows = document.getElementById(tblId).rows;
        for (i = 0; i < rows.length; i++) {
            var _row = rows[i];
            _row.onclick = null;
            _row.onclick = function () {
                return function () {selectRow(this);};
            }(_row);
        }
    }
    catch (err) { }
}
function selectRow(row) {
   row.cells[0].firstChild.checked = !row.cells[0].firstChild.checked;
   row.cells[2].firstChild.checked = row.cells[0].firstChild.checked;
}

Working jsfiddle demo at: https://jsfiddle.net/t6nsxgnz/ Practical implementation at: http://busny.net

You can further customize this solution pertinent to your task by modifying the selectRow(row) function:

function selectRow(row) {
   row.cells[0].firstChild.checked = // add your code for the 1st CheckBox
   row.cells[2].firstChild.checked = // add your code for the 2nd CheckBox
}

Another variation of this functionality coded in jQuery can be found in online pop-quiz engine (http://webinfocentral.com), implemented via the follwoing code snippet:

// toggle Checkboxes on row click
$(Table1 tr').click(function (event) {

    // find the checkbox in the row
    var _chk = $(this).find('input:checkbox');


    if (!($(event.target).is("checkbox"))) {
        $(_chk).prop('checked', !$(_chk).prop('checked'));
    }
});

In this case, Row Click (at any place of the Row) or CheckBox Click events will toggle the state of that particular CheckBox. The state of other CheckBoxes can be synchronized with this one (by using "siblings" property, for example). Hope this may help.

Alexander Bell
  • 7,842
  • 3
  • 26
  • 42
  • Thank you Alex. Your code works great. But I think there is a small problem, In the first column, the click works on the row, but not on the checkbox. If I click in the empty space of the column, the checkbox is getting checked. If I try to click on the checkbox, the checkbox isn't getting checked. But coming to the last column, the click on the checkbox is working! weird :P – ShellZero Mar 28 '16 at 17:45
  • 1
    You are welcome. This is just a demo sample, which could be further customized using the core coding technique I've described (see my extended answer). Best regards, – Alexander Bell Mar 28 '16 at 18:33