Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace html checkbox with X [closed]

I'm trying to replace a checkbox on a form with a red X. Basically, I want the the form functionality to stay the same but I don't want the display to be a box to check but rather a red x to click. I'm not sure how to replace the checkbox icon though.

like image 852
Ben Davidow Avatar asked Feb 11 '26 03:02

Ben Davidow


1 Answers

You can't replace it because it is a browser-specific implementation and you will notice that it looks different in different browsers. However, with a little bit of effort you can write your own. A minimalistic example would be to create the following html structure...

<div>
    <span class="chk" unchecked></span>
    <input type="checkbox" />
</div>

Hide the checkbox and style the span to look the way you want to...

.chk
{
    display:inline-block;
    width:13px;
    height:13px;
    border-radius: 3px;
    padding:2px;
    border:1px #ccc solid;
    cursor:pointer;
}
.chk[checked]{
    background:url(your-checked_image.png);
}
.chk[unchecked]{
    background:url(your_own_image.png);
}
input[type=checkbox]
{
    display:none;
}

And then, you will need to intersect the click event to change the background image, keep track of checked state and toggle the checkbox. Notice that you will still need the checkbox even if it is hidden in case you need to submit some state using a form tag. I do all of that with jQuery which makes everything pretty easy...

$(function(){
    $('.chk').click(function(){
        if($(this).attr('checked') == undefined)
        {
            $(this).attr('checked',"");
            $(this).removeAttr('unchecked');
            $('input[type=checkbox]').prop('checked', true);
        }
        else
        {
            $(this).removeAttr('checked');
            $(this).attr('unchecked',"");
            $('input[type=checkbox]').prop('checked', false);
        }
    });
});

I put together a JS Fiddler that you can play with.

like image 73
Leo Avatar answered Feb 13 '26 08:02

Leo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!