开发者

How can I create checkbox for images using jquery

I was trying to create a checkbox for images where if we have multiple images I can select 3 or 4 images before proceeding ahead. I have seen this kind of thing but I don't know how to create the same using jquery.

For example in this image I would like to give an option that if some one clicks on the image it gets selected. User can select multiple images like this. Is it possible using jquery? or is there a plugin which 开发者_Python百科can help me to achieve this.

How can I create checkbox for images using jquery


This may be sufficient for your needs. Of course you can edit the script and css to be styled how you like:

$('.image-checkbox-container img').live('click', function(){
    if(!$(this).prev('input[type="checkbox"]').prop('checked')){
        $(this).prev('input[type="checkbox"]').prop('checked', true).attr('checked','checked');
        this.style.border = '4px solid #38A';
        this.style.margin =' 0';
    }else{
        $(this).prev('input[type="checkbox"]').prop('checked', false).removeAttr('checked');
        this.style.border = '0';
        this.style.margin = '4px';
    }
});

CSS:

.image-checkbox-container input[type="checkbox"]{
    display: none;
}

.image-checkbox-container img{
    border: 0;
    margin: 4px;
}

Here is a JSFIddle Example


One of many possible implementations. Here I assume you generate a list of images and corresponding checkboxes beforehand (not with javascript).

HTML (snipped):

<div id="selectable_images">
   <img src="/image1.jpg" rel="ch_image_1"/>
   <input style="display:none" type="checkbox" id="ch_image_1" value="image1.jpg"/>

   <img src="/image2.jpg" rel="ch_image_2"/>
   <input style="display:none" type="checkbox" id="ch_image_2" value="image2.jpg"/>

   <img src="/image3.jpg" rel="ch_image_3"/>
   <input style="display:none" type="checkbox" id="ch_image_3" value="image3.jpg"/>
</div>

JS (jQuery):

$(function() {
    $("#selectable_images img").click(function() {
       var $this = $(this);
       if ($this.hasClass('selected')) {
           $("#"+this.rel).attr('checked', false);
           $this.removeClass('selected');
       } else {
           $("#"+this.rel).attr('checked', true);
           $this.addClass('selected');
       }
    })
}

By clicking on the images corresponding checkboxes would be toggled. The selected image would get "selected" class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜