Or Weinberger
Or Weinberger

Reputation: 7482

jQuery onclick div checks a checkbox

I have the following HTML code:

<div class="member">
    <input type="checkbox" value="64" style="display:none;" name="memberId[]" />
    <div class="memberInfo">John Doe</div>
</div>

I'm trying to get a jQuery script that when a visitor presses the member div it will change the background color, and check the memberId checkbox.

How should such a jQuery script look like?

Thanks,

Upvotes: 2

Views: 3123

Answers (3)

<script type="text/javascript">
    jQuery(document).ready(function (){
        $(".member").click(function() {
            $("input[name=memberId]").attr('checked', true);
            $(this).css('background-color','#F00');
        });

    });
</script>

Edit: The others were way faster than me :(

Upvotes: 3

lonesomeday
lonesomeday

Reputation: 238065

You should probably do this with toggle which allows you to set two handlers: one for the first time a handler is triggered and then one for the next time, repeating as necessary.

$('.member').toggle(function() { // first time
    $(this).css('background-color', '#ff0000')
           .find('input:checkbox').attr('checked', true);
}, function() { // second time
    $(this).css('background-color', '#ffffff')
           .find('input:checkbox').attr('checked', false);
});

Upvotes: 3

The Scrum Meister
The Scrum Meister

Reputation: 30141

$('.member').click(function(){
    $(this).css('background-color','#ABC098');
    $(this).find("input[type='checkbox']").attr('checked',true)
});

Upvotes: 0

Related Questions