开发者

Can I disable a checkbox but still have its events triggered?

modified question after answer to use onclick="$( '#co1' ).attr( 'checked', true );" this works great with the disabled="disabled" attribute.....

but...The $aBoxes.change(function(){ does not seem to work with onclick="$( '#co1' ).attr( 'checked', true );"

Original question.....

I was told that "When element is disabled, events are also disabled."

I would like to disable a checkbox, but have an event triggered by clicking a link.

I have this jquery:

var $aBoxes = $('#co1,#co2,#co3');
$aBoxes.change(funct开发者_JS百科ion(){
  // check if all are checked based on if the number of checkboxes total
  // is equal to the number of checkboxes checked
  if ($aBoxes.length == $aBoxes.filter(':checked').length){
      $('#a1').hide();
      $('#a2').show();
  }else{
    $('#a1').show();
    $('#a2').hide();
  }
});


<div id="a1">
a1 div
</div>

<div id="a2" style="display:none;">
a2 div
</div>

<div class="content">
<ul>
<li>
<input disabled="disabled" id="co1" name="co1" type="checkbox" <?php if($mychecklist->co1==1) echo 'checked' ?>/>
<a href="http://bbc.co.uk" target="_blank" onclick="$( '#co1' ).attr( 'checked', true );">Link 1</a>
</li>
<li>
<input disabled="disabled" id="co2" name="co2" type="checkbox" <?php if($mychecklist->co2==1) echo 'checked' ?>/>
<a href="http://bbc.co.uk" target="_blank" onClick="$( '#co2' ).attr( 'checked', true );">Link 2</a>
</li>
<li>
<input disabled="disabled" id="co3" name="co3" type="checkbox" <?php if($mychecklist->co3==1) echo 'checked' ?>/>
<a href="http://bbc.co.uk" onClick="$( '#co3' ).attr( 'checked', true );">Link 3</a>
</li>
</ul>
</div>

The onclick event on the link works great for checking the checkbox, but i would like to disable using disabled="diasabled" the checkbox and still have it working. This is so the user has to click on the link for the checkbox to be checked, rather than bypassing this step and checking the checkbox themselves.

Thanks in advance for any help.


It's not clear whether you want to check the disabled checkbox using an <a> link or trigger a click event attached to the checkbox. If the former, you can use $( '#tt2' ).attr('checked', !$( '#tt2' ).attr('checked') ) to toggle the checkbox or $( '#tt2' ).attr( 'checked', true ) to check it. If the latter, the click event should still run even if the checkbox is disabled.


If you need to both check the box and trigger an event just use both techniques.

<a href="http://bbc.co.uk" target="_blank" 
    onclick="$( '#co1' ).attr( 'checked', true ).trigger( 'change' );">


Use the readonly attribute for your checkbox!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜