Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect .click() on disabled checkbox

js/jQuery:

$('input[type=checkbox]').click(function(){
  // Does not fire if I click a <input type="checkbox" disabled="disabled" />
});

How do I make something happend in jQuery when someone clicks a disabled checkbox?

like image 503
Lilleman Avatar asked Sep 16 '12 16:09

Lilleman


2 Answers

Reading over the comment again regarding using readonly from JoãoSilva. You could use that and connect it with some logic in the click event.

Using readonly gives you the disabled look, just like disabled does but it still lets you click it.

Use readonly like this:

<input type="checkbox" readonly="readonly">​

Then in your script cancel the event if readonly is set.

$('input[type=checkbox]').click(function() {
    var isReadOnly = $(this).attr("readonly") === undefined ? false : true;

    if (isReadOnly) {
        return false;
    }

    // other code never executed if readonly is true.
});
​

DEMO

like image 55
Nope Avatar answered Sep 17 '22 16:09

Nope


You will not be able to capture the click event reliably across all browsers. Your best bet is to place a transparent element above to capture the click.

HTML

<div style="display:inline-block; position:relative;">
  <input type="checkbox" disabled="disabled" />
  <div style="position:absolute; left:0; right:0; top:0; bottom:0;"></div>
</div>​

JavaScript

$(':checkbox:disabled').next().click(function(){
    var checkbox = $(this.prevNode);
    // Does fire now :)
});

Note: This is an idea from this question which I improved on.

like image 38
iambriansreed Avatar answered Sep 17 '22 16:09

iambriansreed