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" na开发者_如何转开发me="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>
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.
精彩评论