0

I'm new at javascript and jquery and have used this site (and others) to try and figure out why the click function in the fiddle below does not properly work.

When you run the code, you'll see a checkbox and textarea, even when the checkbox is not selected. The correct behavior should be; only show the textarea when the checkbox is selected. I'm sure i'm missing something simple here.

Any help is much appreciated.

fiddle

HTML:

<input type="checkbox" id="OtherAdv" name="OtherAdv" value="1" data-mini="true" /><label for = "OtherAdv">Other?</label>

<textarea rows="4" cols="50" class="formfont_small" id="OtherAdvDiag" name="OtherAdvDiag" data-mini="" placeholder="Please list others"></textarea>

Javascript:

$(document).ready(function () {
     $('#OtherAdv').click(function () {
         var $foo = $(this);
         if ($foo.is(':checked')) {
             $('#OtherAdvDiag').show();
         } else {
             $('#OtherAdvDiag').hide();
         }
     });
 });
1
  • 1
    You're not hiding anything initially, and it seems to work if you check, then uncheck the checkbox. A $('#OtherAdvDiag').hide(); before your click function would seem to do what you want. Commented Jan 5, 2015 at 20:00

3 Answers 3

2

The problem is you're not accounting for the starting state of the checkbox - you're acting only on future state changes.

This can be remedied in several ways. If you know the checkbox will always begin unchecked, you could simply hide the textarea in your CSS. Or, for more dynamism, you can use trigger() to fire the event on load, in which case your existing callback will take care of the problem, just as if someone had actually toggled the checkbox.

Updated code:

$(function () {
    $('#OtherAdv').on('change', function () {
        $('#OtherAdvDiag')[$(this).is(':checked') ? 'show' : 'hide']();
    }).trigger('change');
});

I also cleaned up and optimised your code a little, in several areas. In particular, use change, not click, events with checkboxes, as the former takes into account toggles done via non-mouse means also, e.g. keyboard.

Sign up to request clarification or add additional context in comments.

Comments

0

It seems to work fine, the textarea just isn't hidden by default. You can hide it with CSS, for example:

#OtherAdvDiag {
    display: none;
}

Or if you want to keep the functionality with the JavaScript, just hide it once when the page loads:

$('#OtherAdvDiag').hide();

Comments

0

Here you go

You need to hide the textarea when the page loads by including

style="display:none"

1 Comment

Why not use the handy input box for CSS instead of an inline style in the markup?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.