最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery click on td to toggle checkbox - Stack Overflow

programmeradmin1浏览0评论

As the title suggests, I want to be able to click on a table td OR the checkbox itself to toggle a checkbox on or off. The solution below works when clicking on the td, but for some reason when you click on the checkbox nothing happens. Any ideas as to what is going on here?

$('td').click(function (e) {
    // Toggle checkbox
    $('input:checkbox', this).prop('checked', function (i, value) {
        return !value;
    });
});

Thanks!

/

As the title suggests, I want to be able to click on a table td OR the checkbox itself to toggle a checkbox on or off. The solution below works when clicking on the td, but for some reason when you click on the checkbox nothing happens. Any ideas as to what is going on here?

$('td').click(function (e) {
    // Toggle checkbox
    $('input:checkbox', this).prop('checked', function (i, value) {
        return !value;
    });
});

Thanks!

http://jsfiddle/Littlebob/56CnR/

Share Improve this question edited May 13, 2014 at 9:24 Littlebob asked May 13, 2014 at 8:29 LittlebobLittlebob 1534 silver badges15 bronze badges 3
  • 1 What code do you have already? – haxtbh Commented May 13, 2014 at 8:30
  • 4 see jsfiddle/arunpjohny/vmQ6e/1 – Arun P Johny Commented May 13, 2014 at 8:39
  • Sorry, added in code and a jsfiddle link – Littlebob Commented May 13, 2014 at 9:24
Add a ment  | 

3 Answers 3

Reset to default 9

It's because the <input> checkbox is inside the <td> and you have attached click event to the <td>

to overe this, Check for the target type and if it's not input checkbox, you need to process it.

DEMO

$('td').click(function (event) {
    if (!$(event.target).is('input')) {
       $('input:checkbox', this).prop('checked', function (i, value) {
        return !value;
       });
    }
});

refer

event.target

jQuery.is()

I don't know the context of your code, but you really shouldn't need any jQuery/JavaScript here. This can be done simply with the addition of the label element:

HTML

<table>
    <tr>
        <td>
            <label><input type="checkbox" name="something" value="0"/></label>
        </td>
    </tr>
</table>

CSS

td {
    background-color: #eee;
}

label {
    padding: 20px;
    cursor: pointer;
    display: block;
}

See the demo

$(document).ready(function () {
$(document).on('click', 'tbody td', function (e) {
    e.stopPropagation();
    var checked= $(this).find('input[type="checkbox"]');
    checked.prop('checked', !checked.is(':checked'));
    $(this).toggleClass('selected'); // or anything else for highlighting purpose
});
$(document).on('click', 'input[type="checkbox"]', function (e) {
    e.stopPropagation();
    $(this).parent().toggleClass('selected'); // or anything else for highlighting purpose
});
});

check this JSFiddle

发布评论

评论列表(0)

  1. 暂无评论