Search code examples
javascriptjquerycheckboxhideunchecked

Checking a different checkbox hides input field


I have an input field that only shows when the option "Other" is checked. The input field fades out when I uncheck the "Other" checkbox, but I would also like the input field to fade out say if, instead of unchecking the "Other" checkbox I check another checkbox of the same group. Therefore, the "Other" input field should not be visible unless "Other" is checked. I have the javascript partially working, but when I check another checkbox the "Other" input field stays visible.

HTML

<input type="checkbox" id="residence_check" name="found"/>
<label for="residence_check">
    Residence
</label>
<input type="checkbox" id="tradeshow_check" name="found"/>
<label for="tradeshow_check">
    Tradeshow
</label>
<input type="checkbox" id="office_check" name="found"/>
<label for="office_check">
    Office Building
</label>
<input type="checkbox" id="check_other" value="found_other" name="found"/>
    <label for="check_other">
    Other
</label>
<input type="text" id="check_input" placeholder="Other"/>

Javascript

$('#check_other').change(function() {
    if($(this).is(":checked")) {
        $('#check_input').fadeIn();
    } else {
        $('#check_input').fadeOut('fast');
            }
});

Solution

  • From what I gather from your use case is that you don't want to use checkboxes, but radio buttons. If that is the case, this would be a good way to implement what you want:

    http://jsfiddle.net/AeP58/1/

    $('input[type=radio]').on('change', function() { //event on all radio buttons
        if($(this).attr('id') == 'check_other' && $(this).prop('checked')) {
            $('#check_input').fadeIn();
        } else {
            $('#check_input').fadeOut('fast');
        }
    });
    

    If you do want checkboxes, you could change the code a bit and probably get what you want.