mardi 28 avril 2015

Click table row to select checkbox and disable/enable button jquery

HTML:

<table class="vi_table">
    <thead>
        <tr>
            <th><input type="checkbox" class="v_checkbox"/>Select</th>
            <th>ID</th>
            <th>A</th>
            <th>B</th>
        </tr>
    </thead>
    <tbody>
        <tr class="pv">
            <td><input type="checkbox" class="v_checkbox"/></td>
            <td>5</td>
            <td>Content 2</td>
            <td>Content 3</td>
        </tr>
        <tr class="pv">
            <td><input type="checkbox" class="v_checkbox"/></td>
            <td>1</td>
            <td>Content 2</td>
            <td>Content 3</td>
        </tr>
        <tr class="pv">
            <td><input type="checkbox" class="v_checkbox"/></td>
            <td>9</td>
            <td>Content 2</td>
            <td>Content 3</td>
        </tr>
    </tbody>
</table>

<input id="percentage_submit_button" name="commit" type="submit" value="Set % for Selections">

Css:

.diff_color {
    background: gray;
}

.vi_table {
    background: #c3ced6;
    border: 1px solid black;
    margin-bottom: 30px;
    padding: 5px;
}

.vi_table thead tr th {
    border: 1px solid black;
}

Jquery:

$(document).ready(function () {
    $(document).on('click', '.vi_table tbody tr', function (e) {
        var submit = $('#percentage_submit_button');
        var checked= $(this).find('input[type="checkbox"]');

        submit.prop('disabled', true);

        checked.prop('checked', !checked.is(':checked'));

        if($('.v_checkbox').is(':checked')) {
            $(this).closest('tr').addClass('diff_color');
            submit.removeAttr('disabled');
        } else {
            $(this).closest('tr').removeClass('diff_color');
            submit.prop('disabled', true);
        }
    });


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

});

So Far - Fiddle

I want to select the checkbox by clicking anywhere on the row including the checkbox. I would like to enable and disable the button if any one of the checkbox is selected in the tbody.

clicking the Selectall checkbox needs to select all the rows and enable the button.

I gave the example of what I have tried so far, but I would like to make this clean like non repeating code. how can I make this code simple and more efficient way?

Thanks




Aucun commentaire:

Enregistrer un commentaire