Show or hide table row if checkbox is checked

Duncan Luk picture Duncan Luk · Dec 23, 2014 · Viewed 17.1k times · Source

I want to hide a table row (with input fields inside) when a checkbox is checked. I found something that works:

HTML

<table>
    <tr id="row">
        <td><input type="text"></td>
        <td><input type="text"></td>
    </tr>
    <tr>
        <td><input type="checkbox" id="checkbox">Hide inputs</td>
    </tr>
</table>

Script

$(document).ready(function () {
    $('#checkbox').change(function () {
        if (!this.checked) 
            $('#row').fadeIn('slow');
        else 
            $('#row').fadeOut('slow');
    });
});

Fiddle

But this only works if the checkbox is not checked already. So if the checkbox is checked at the beginning, I want the table row to be hidden. How do I do this?

Please note that I don't know much about JavaScript, but I really need this

Answer

Mohamad Shiralizadeh picture Mohamad Shiralizadeh · Dec 23, 2014

trigger .change() event after you attach events:

$(function () {
    $('#checkbox1, #checkbox2').change(function () {
        var row = $(this).closest('tr').prev();

        if (!this.checked)
            row.fadeIn('slow');
        else 
            row.fadeOut('slow');

    }).change();
});

Note: I make code shorter.

jsfiddle