Abdullah Gheith
Abdullah Gheith

Reputation: 520

Check checkbox when pressing on table row

I am trying to allow my users to press on the table row to check a checkbox.

<table>
    <tr>
        <td onclick="toggleIt(this)">
            <input type="checkbox"/> Option 1
        </td>
    </tr>
    <tr>
        <td onclick="toggleIt(this)">
            <input type="checkbox"/> Option 2
        </td>
    </tr>
</table>
function toggleIt(myTd) {
   $(myTd).find('input').prop('checked', !$(myTd).find('input').prop('checked'));
}

This works great until you press the checkbox itself, then it wont work. My guess is that the checkbox checks itself, then the javascript is run and it reverses it again.

jsFiddle: http://jsfiddle.net/toxu1v2o/1/

EDIT: Sorry for not clarifying, I need to be able to press the whole td tag, This wont work with labels: http://jsfiddle.net/toxu1v2o/4/

SOLUTION:

Instead of using this, use event. Then check if its the checkbox being pressed or not. Something like this:

http://jsfiddle.net/toxu1v2o/17/

Upvotes: 0

Views: 369

Answers (4)

Rory McCrossan
Rory McCrossan

Reputation: 337560

You don't need JavaScript for this - just wrap the checkbox and the text in a <label /> element:

td {
  background-color: #F0F0F0;
}
label {
  padding: 40px;
  display: block;
}
<table>
  <tr>
    <td>
      <label>
        <input type="checkbox" />Option 1
      </label>
    </td>
  </tr>
  <tr>
    <td>
      <label>
        <input type="checkbox" />Option 2
      </label>
    </td>
  </tr>
</table>

Upvotes: 3

faby
faby

Reputation: 7558

you can try in this way

<table>
    <tr>
        <td> 
            <label for="cb1">Op1</label>
            <input id="cb1" type="checkbox"/>
        </td>
    </tr>
    <tr>
        <td>
          <label for="cb2">Op2</label> 
          <input id="cb2" type="checkbox"/>
        </td>
    </tr>
</table>

Upvotes: 1

Millzie
Millzie

Reputation: 332

Does this work for you? And what version of jquery are you using?

$('td').click(function(){
   $('input[type="checkbox"]').attr('checked', 'true');
});

Upvotes: 0

atiquratik
atiquratik

Reputation: 1300

Wrap both your input & key with <label> tag. Hope it'll work!

Upvotes: 0

Related Questions