Search code examples
javascripthtmlcssinputrow

Select a radio input when the row is clicked


I need to have a radio input selected when a user clicks anywhere in the row and highlight the row when the mouse goes trough it. I have been toying with some options but cannot get anything to work apart of those with jquery/javascript, but I'm sure there's some way to make it work with plain html/css.

I know that can be done toying with label+inputs plus "tables" or "display:table-row;" or widths but I 'm just not able to make it work. I'll appreciate any help.


Solution

  • I managed to solve it after hours of reading and testing. Here you have even IE8+ compatible, works for input radio and checkboxes. You can change the width and the colours as you need. The CSS:

    .div-table{
        display:table;
        width:100%;
    }
    .div-table-row{
        display: table-row;
        width: auto;
        clear:both;
    }
    .div-table-row:hover{
        background-color: #ecf0f1;
    }
    .div-table-col>input{
        float:left;/*fix for  buggy browsers*/
        display:table-column;
        width: 6%;
        outline: none !important;
    }
    .div-table-col>label{
        float:left;/*fix for  buggy browsers*/
        display:table-column;
        width: 94%;
    }
    .div-table-col>input:checked + label{
        background-color: #ecf0f1;
    }
    

    And the HTML looks like this(add as many rows as you need):

    <form action="" class="div-table">
    <div class="div-table-row">
        <div class="div-table-col">
            <input type="radio" name="nametest" id="t1" value="1">
            <label for="t1"> Blablabla</label>
        </div>
    </div>
    <div class="div-table-row">
        <div class="div-table-col">
            <input type="radio" name="nametest" id="t2" value="2">
            <label for="t2"> Blablabla Blablabla Blablabla Blablabla</label>
        </div>
    </div>
    </form>