How to check .click () is disabled

JS / jQuery:

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

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

+8
javascript jquery
source share
4 answers

Read the comment on using readonly from JoãoSilva . You can use this and associate it with some logic in the click event.

Using readonly gives you a disabled look, like disabled does, but it still allows you to click it.

Use readonly as follows:

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

Then in the script, cancel the event if read-only 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

+10
source share

You cannot reliably capture the click event in all browsers. It’s best to place a transparent element above to capture a 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 that I have improved.

+8
source share

You cannot ... but you can fake it by placing a div above the input with a transparent background and defining a click function on that div.

 $('input').each(function(){ if(true == ($(this).prop('disabled'))){ var iTop = $(this).position().top; var iLeft = $(this).position().left; var iWidth = $(this).width(); var iHeight = $(this).height(); $('body').append('<div class="disabledClick" style="position:absolute;top:'+iTop+'px;left:'+iLeft+'px;width:'+iWidth+'px;height:'+iHeight+'px;background:transparent;"></div>'); } }); //delegate a click function for the 'disabledClick'. $('body').on('click', '.disabledClick', function(){ console.log('This is the click event for the disabled checkbox.'); }); 

Here's the working jsFiddle

+1
source share

I do not see another option for adding a block layer <div> on top of the checkbox. Therefore, the solution should be as follows:

 function addDisabledClickHandler(el, handler) { $("<div />").css({ position: "absolute", top: el.position().top, left: el.position().left, width: el.width(), height: el.height() }).click(handler).appendTo("body"); } var el = $("input[type='checkbox']"); addDisabledClickHandler(el, function() { alert("Clicked"); });​ 

DEMO: http://jsfiddle.net/q6u64/

0
source share

All Articles