Jerahmeel Acebuche
Jerahmeel Acebuche

Reputation: 2369

how to check a specific image with input checkbox

I have this code that I'm still modifying. But I'm still having a hard time. I'm new in jquery . I'm planning to make a multiple checkbox with image. please check my code. It's not working. my sample code is two checkbox. Im planning to put it on array so that I could put more than two checkboxes with image. instead of making jquery code in each of checkbox.

here is my code

html

<form id="form1">
    <img src="https://cdn2.iconfinder.com/data/icons/windows-8-metro-style/128/unchecked_checkbox.png" title="blr" id="blr" class="" />
    <input type="checkbox" id="imgCheck[]" name="imgCheck" value="barney" />

    <img src="https://cdn2.iconfinder.com/data/icons/windows-8-metro-style/128/unchecked_checkbox.png" title="blr" id="blr" class="" />
    <input type="checkbox" id="imgCheck[]" name="imgCheck" value="barney2" />

    <input type="submit" value="Submit" />
</form>

jquery

$('img').on('click', function(){
        var $$ = $(this)
        if( !$$.is('.checked')){
            $$.addClass('checked');
            $('input[id=imgCheck]').prop('checked', true);
        } else {
            $$.removeClass('checked');
            $('input[id=imgCheck]').prop('checked', false);
        }
    })

style

.checked {border:solid 2px red}

Upvotes: 0

Views: 60

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

Try

$('img').on('click', function () {
    var $$ = $(this)
    //toggle the checked state
    $$.toggleClass('checked');
    //set the next checkbox's state in synch with the checked state of the image
    //from the given markup we can assume that an image will always be related to the next sibling element which will be checkbox
    $$.next('input').prop('checked', $$.hasClass('checked'));
})

Demo: Fiddle

Upvotes: 1

Related Questions