简体   繁体   中英

jquery click event handling

When i click TD the input element inside should be selected and vise-versa,

I wrote the below code using jquery which is working fine but when i click on the checkbox it is not working the way a checkbox works, any ideas how to hadle this

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function (){
    $(".mainTable td").click(function (){
        var obj = $(this).children('input[type=checkbox]');
        var bool = obj.prop("checked");
        if(obj.length > 0){
           obj.attr("checked",!bool); 
        }
    });
});
</script>

<table cellpadding=10 border=1 class='mainTable'>
<tr>
<td><input type="checkbox" /></td>
<td><input type="checkbox" /></td>
</tr>
<table>

That's because events bubble up, you can use stopPropagation method.

$(document).ready(function (){
    $(".mainTable td").click(function (){
        $('input[type=checkbox]', this).prop('checked', function(i, checked){
           return !checked; 
        })
    }).find('input[type=checkbox]').click(function(e){
        e.stopPropagation();
    })
});

http://jsfiddle.net/vs4ma/

$(".mainTable td").click(function (event){
    if (event.target.nodeName === 'INPUT') {
        return;
    } else {
        var obj = $(this).children('input[type=checkbox]');
        var bool = obj.prop("checked");
        if(obj.length > 0){
           obj.attr("checked",!bool); 
        }
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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