tctc91
tctc91

Reputation: 1363

control a checkbox via an IMG using jquery

I want to control the checked state of a checkbox when a user clicks on an image with the class of ".latinAmerica" within the page. Each click should check/uncheck it each time.

I've tried a ton of different methods but I can't find anything suitable for checkboxes.

EG:

$('.latinAmerica').click(function () {  
    if($('input:checkbox[name=theName]:nth(0)').is(':checked')) {
        $('input:checkbox[name=theName]:nth(0)').attr('checked',true);
    } else {
        $('input:checkbox[name=theName]:nth(0)').attr('checked',false);
    }   
});

or

$('.latinAmerica').click(function () {  
    $("input:checkbox[name=theName]:nth(0)").prop("checked", true);
});

I did get this method working with radio buttons:

$('.latinAmerica').click(function () {  
    $('input:checkbox[name=theName]:nth(0)').attr('checked',true);
});

But no luck with checkboxes.

What am I doing wrong :(

Thanks.

Upvotes: 0

Views: 179

Answers (2)

amit_g
amit_g

Reputation: 31250

The if condition is wrong so it must not doing anything i.e. checkedbox is checked when it is already checked and unchecked when it is already unchecked.

$('.latinAmerica').click(function () {  
    if($('input:checkbox[name=theName]:nth(0)').is(':checked')) {
        $('input:checkbox[name=theName]:nth(0)').attr('checked',false);
    } else {
        $('input:checkbox[name=theName]:nth(0)').attr('checked',true);
    }   
});

Upvotes: 1

Interrobang
Interrobang

Reputation: 17434

$(function() {
    $(".latinamerica").click(function() {
        var cb = $("input[name='theName']");
        if(cb.is(":checked")) {
            cb.prop("checked", "");
        } else {
            cb.prop("checked", "checked");
        }
    });
});

Fiddle: http://jsfiddle.net/JFDxj/

Upvotes: 1

Related Questions