开发者

Simple way to replace check boxes with images in jQuery without using plugins

I would like to replace checkboxes with images however all I have come across are jQuery p开发者_如何学编程lugins. Is such a feature achievable in a few lines rather than a plugin?

Thanks.


Here is my take, you need two images imgOn and imgOff for checked and unchecked states of check box. This needs ID attribute on each checkbox to be set to modify it on clicking on the image.

<ul>
   <li><input type="checkbox" id="chk1" checked="checked"/> Check 01</li>
   <li><input type="checkbox" id="chk2"/> Check 02</li>
</ul>   
<script type="text/javascript">
    var imgOn='imgOn.png';
    var imgOff='imgOff.png';
    $(function(){
        $("input:checkbox").each(function(){            
    $(this).css("display","none");
    if($(this).is(":checked")){ 
        $(this).after($(document.createElement("img"))
        .attr({src:imgOn,title:'Checkbox',id:$(this).attr("id")})
            .addClass("chkBoxImg"));
    }else{
        $(this).after($(document.createElement("img"))
        .attr({src:imgOff, title:'Checkbox',id:$(this).attr("id")})
        .addClass("chkBoxImg"));
    }});
    $("img.chkBoxImg").click(function(){
        i= "input#"+$(this).attr("id")+":checkbox";
        alert($(i).attr("checked"));
        s=$(this).attr("src");
        if(s==imgOn){
            $(this).attr("src",imgOff);
        $(i).attr("checked",false);
        }else{
        $(this).attr("src",imgOn);
        $(i).attr("checked",true);
        }});
});
</script>


Check out the possibilities inherent with the function replaceWith()

http://docs.jquery.com/Manipulation/replaceWith

Not tested but try something like:

$("input:checkbox").replaceWith("<img src='MyImg.gif'>");

I'm pretty sure you'll be wanting more than this, but I suggest its a good starting point.


Well, the problem is that you need to maintain the state of the psuedo-checkbox, just as if it were a real checkbox. There's no way you're going to be able to do with with just a few lines.


Why not put the images on top of the checkboxes, and then have them delegate all the "click" events? That way your checkboxes will still be there at form submission time.

You really should consider the usability aspects of forcing your users to recognize checkboxes that look different from checkboxes on other sites.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜