2

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>
2
  • 3
    WHy are you using prop in one case and attr in another? Commented Mar 14, 2013 at 4:38
  • and does obj.attr("checked",!bool); this do.? Commented Mar 14, 2013 at 4:42

2 Answers 2

3

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/

Sign up to request clarification or add additional context in comments.

Comments

1
$(".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); 
        }
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.