dman
dman

Reputation: 31

Toggle visibility of text box based on status of check box--jquery

So I have a list of races for a survery form. there is a box named 'other specify' for those people that don't meet any of the other criteria. I need a text book to become visible when 'other specify' is checked, and to dissappear when it's not. I have been able to make the box appear when another is checked, but not dissappear when it was unchecked. Any help would be greatly appreciated. Thanks.


Jscript

<script type="text/javascript" src="jquery.js">
 <script language="JavaScript">

 $(function(){ 
  $('#other').click(function(){ 
  $('#otherrace').toggle(
          function(event) {
            $(event.target).css('visible');
          },
          function(event) {
            $(event.target).css('hidden');
          }
        );
      });


    </script>

html

<input type="checkbox" name="race"  id="other"value="other" />Other, specify<br />
<div style="visibility:hidden" id="race"><input type="text" name="fname" size="25" maxlength="25" id="otherrace" /></div>

Upvotes: 1

Views: 5672

Answers (1)

user113716
user113716

Reputation: 322622

Do it this way:

Example: http://jsfiddle.net/patrick_dw/K3kvE/

$('#other').change(function(){ 
    $('#otherrace').parent().css( 'visibility', this.checked ? 'visible' : 'hidden' );
});

or use display:none instead of visibility:hidden and do this:

Example: http://jsfiddle.net/patrick_dw/K3kvE/1/

$('#other').change(function(){ 
    $('#otherrace').parent().toggle( this.checked );
});

The way you were using .toggle() was as a "toggle event", which means you were effectively assigning a click event that toggles between executing the functions you pass it.

Because it is the parent of otherrace that is being hidden, you need to traverse up to it using .parent(), then set its visibility property to hidden or visible depending on the state of the checkbox.

The second solution changes from using visibility property to using display so that toggle() can be called in a different manner. The way it is being called now, it toggles between show() and hide(), which set the display property from none to its original setting and back.

Upvotes: 2

Related Questions