Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tick a checkbox in a table cell by clicking anywhere in the table cell

I'm trying to figure out how to do this, but I can't find the information anywhere. Basically, I have a table with each cell containing a checkbox. I want to be able to tick the checkbox by clicking anywhere within the cell. I can't figure out how to do it, Javascript would be the best type of solution for me but I could also use jQuery.

Here is a row of my table I wish to do this in:

<tr>
    <td><center>9:00 - 10:00</center></td>
    <td><center><input type="checkbox" name="free" value="mon09"></center></td>
    <td><center><input type="checkbox" name="free" value="tue09"></center></td>
    <td><center><input type="checkbox" name="free" value="wed09"></center></td>
    <td><center><input type="checkbox" name="free" value="thu09"></center></td>
    <td><center><input type="checkbox" name="free" value="fri09"></center></td>
</tr>
like image 330
cs_irl Avatar asked Mar 16 '12 14:03

cs_irl


3 Answers

Why not use a pure CSS solution? This makes use of label tag to achieve what you desire.

<tr>
    <td><center>9:00 - 10:00</center></td>
    <td><label><input type="checkbox" name="free" value="mon09"></label></td>
    <td><label><input type="checkbox" name="free" value="tue09"></label></td>
    <td><label><input type="checkbox" name="free" value="wed09"></label></td>
    <td><label><input type="checkbox" name="free" value="thu09"></label></td>
    <td><label><input type="checkbox" name="free" value="fri09"></label></td>
</tr>

<style type="text/css">
    td label { 
       display: block;
       text-align: center;
    }
</style>

For a more advanced working demonstration, check this out http://jsfiddle.net/8q5TQ/7/

like image 140
Sushil Avatar answered Oct 18 '22 08:10

Sushil


You may try this, check this fiddle

$(function(){
    $('table tr td').on('click', function(e){
        if(e.target.type=="checkbox")
        {        
            if($(this).is(':checked')) $(this).attr('checked', false);
            else $(this).attr('checked', true);
            return;
        }
        else
        {
            if($(this).find('input:checkbox').is(':checked')) 
                $(this).find('input:checkbox').attr('checked', false);
            else
                $(this).find('input:checkbox').attr('checked', true);
        }
    });
});
like image 34
The Alpha Avatar answered Oct 18 '22 08:10

The Alpha


I was able to get it working after applying the 'for' attribute to the label element:

<tr>
    <td><center>9:00 - 10:00</center></td>
    <td><label for="mon09"><center><input type="checkbox" name="free" value="mon09" id="mon09"></center></label></td>
    <!-- etc. -->
</tr>
like image 28
Kit.net Avatar answered Oct 18 '22 09:10

Kit.net