Question

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');
            }
});
Was it helpful?

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.

OTHER TIPS

If you want to have some fun with checkboxes you could try this:

function showHideOtherInput() {
console.log($(this)[0]==$('#check_other')[0]);
        var shouldShow=$('[id$="_check"]:checked').length===0 && $('#check_other').prop('checked');
        console.log(shouldShow);
    if(shouldShow) {
        $('#check_input').fadeIn();
    } else {
        $('#check_input').fadeOut('fast');
            }
}
$('#check_input').hide(); //since nothing is selected at this point just hide the input
$('#check_other').change(showHideOtherInput);
//for each XXXX_check checkbox trigger the show or hide function
$('[id$="_check"]').each(function(ix,el){$(el).change(showHideOtherInput)});

Hope this works for you. :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top