Reputation: 607
I have a div in a form (#sides
) that I only want displayed when one checkbox (.opp-choice-checkbox
) is not checked. Here's the code I have right now:
jQuery ->
if !$(".opp-choice-checkbox").checked
$("#sides").hide()
$(".opp-choice-checkbox").click ->
$("#sides").slideToggle()
A similar question is asked a lot, but the difference with my question is that when I go to edit the object the form is for, sometimes the checkbox is checked by default. In that situation, I want the div to be showing when the page is loaded. The code I have right now hides the div by default, regardless of whether or not the checkbox is checked
Upvotes: 1
Views: 97
Reputation: 67505
UPDATED
Your code working perfectly with the little update mentioned below, See Working fiddle for your code:
CoffeeScript :
You have just to add the else
in your condition to show the div if the checkbox
is checked :
jQuery ->
if !$(".opp-choice-checkbox").is(":checked")
$("#sides").hide()
else
$("#sides").show()
$(".opp-choice-checkbox").click ->
$("#sides").slideToggle()
If sometimes you have a chekcked checkbox
by default, you have just to remove condition and replace your coofee code by the following :
jQuery ->
$(".opp-choice-checkbox").change ->
$("#sides").slideToggle()
See fiddle HERE.
I hope this will help.
Upvotes: 1
Reputation: 104775
$(".opp-choice-checkbox")
doesn't have a checked
property - that's a jQuery element. To get the regular DOM elem, use [0]
$(".opp-choice-checkbox")[0].checked
Or, use .is("checked")
$(".opp-choice-checkbox").is("checked")
If this is all attached to a change
or click
event, just run that event on load to trigger the behavior, ($(elem).change(function() { }).change()
)
Upvotes: 1