javascript - click anywhere on a table row and it will check the checkbox its in...? -


i'm trying figure out how this, can't find out. want able click anywhere on table row , check/ unchecked checkbox in. know it's possible because that's phpmyadmin does...

here table row

<tbody> <tr id="1" onclick="selectrow(1)"><td width="20px"><input type="checkbox" id="1" name="1/"></td><td>1</td><td>2011-04-21 22:04:56</td><td>action</td></tr>  <tr id="2" onclick="selectrow(2)"><td width="20px"><input type="checkbox" id="2" name="2/"></td><td>2</td><td>2011-04-21 22:04:56</td><td>action</td></tr>  </tbody> 

<script type="text/javascript"> function selectrow(row) {     var firstinput = row.getelementsbytagname('input')[0];     firstinput.checked = !firstinput.checked; } </script> 

...

<tbody>     <tr onclick="selectrow(this)"><td width="20px"><input type="checkbox" id="chk1" name="chk1/"></td><td>1</td><td>2011-04-21 22:04:56</td><td>action</td></tr>         <tr onclick="selectrow(this)"><td width="20px"><input type="checkbox" id="chk2" name="chk2/"></td><td>2</td><td>2011-04-21 22:04:56</td><td>action</td></tr>   </tbody> 

note: you've got collisions on ids. ids should unique.

here's alternative programmatic binding:

(function () {      function rowclick(e) {          // discard direct clicks on input elements          if (e.target.nodename === "input") return;          // first checkbox          var checkbox = this.queryselector("input[type='checkbox']");          if (checkbox) {              // if exists, toggle checked property              checkbox.checked = !checkbox.checked;          }      }      // iterate through rows , bind event listener      [].foreach.call(document.queryselectorall("tr"), function (tr) {          tr.addeventlistener("click", rowclick);      });  })();
<table>      <tbody>          <tr>              <td>                  <input type="checkbox" id="chk1" name="chk1" />              </td>              <td>1</td>              <td>2011-04-21 22:04:56</td>              <td>action</td>          </tr>          <tr>              <td>                  <input type="checkbox" id="chk2" name="chk2" />              </td>              <td>2</td>              <td>2011-04-21 22:04:56</td>              <td>action</td>          </tr>          <tr>              <td>                  <input type="checkbox" id="chk2" name="chk3" />              </td>              <td>2</td>              <td>2011-04-21 25:30:16</td>              <td>action</td>          </tr>      </tbody>  </table>


Comments