Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show or hide table row if checkbox is checked

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

like image 372
Duncan Luk Avatar asked Dec 09 '22 05:12

Duncan Luk


2 Answers

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

like image 172
Mohamad Shiralizadeh Avatar answered Dec 11 '22 10:12

Mohamad Shiralizadeh


Just call the change event after you initially register it:

$(document).ready(function () {
    $('#checkbox').change(function () {
        if (!this.checked) 
            $('#row').fadeIn('slow');
        else 
            $('#row').fadeOut('slow');
    });
    $('#checkbox').change();
});
like image 35
musefan Avatar answered Dec 11 '22 08:12

musefan