简体   繁体   English

按下表格行时选中复选框

[英]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. 我的猜测是,复选框会自行检查,然后运行javascript并将其再次反向。

jsFiddle: http://jsfiddle.net/toxu1v2o/1/ 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/ 编辑:对不起,我不清楚,我需要能够按整个td标签,这将无法使用标签: http : //jsfiddle.net/toxu1v2o/4/

SOLUTION: 解:

Instead of using this , use event . 代替使用this ,使用event Then check if its the checkbox being pressed or not. 然后检查其复选框是否被按下。 Something like this: 像这样:

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

You don't need JavaScript for this - just wrap the checkbox and the text in a <label /> element: 您不需要JavaScript,只需将checkbox和文本包装在<label />元素中:

 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> 

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> 

Wrap both your input & key with <label> tag. 将您的inputkey<label>标签包裹。 Hope it'll work! 希望能成功!

Does this work for you? 这对您有用吗? And what version of jquery are you using? 您正在使用什么版本的jquery?

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

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

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