3

I have a button which by default is disable, but when a checkbox is checked the button is then enabled. I would like to edit the script to make an alert window when the button is clicked when disabled, to make sure the user knows he/she has to check the checkbox.

My script so far:

<script type="text/javascript">
$('#terms').on('change', function(){
          if ($(this).is(':checked')){
             $('#customButton').removeProp('disabled');
          }
          else{
             $('#customButton').attr('disabled', 'disabled');
          }
       });
</script>

<form id="payment-form" action="chargeCard.php" method="POST" name="payment-form">
<input type="checkbox" id="terms" />
<input type="image"  src="button3.png" id="customButton" value="submit" alt="button" disabled="disabled"/>
</form>
Fulgut98
  • 323
  • 1
  • 2
  • 12
  • You want to trigger event handler on the click of `disabled` button? – Satpal Apr 28 '15 at 08:19
  • I want to trigger a function which, if the button is disabled and clicked an alert window pops up. – Fulgut98 Apr 28 '15 at 08:21
  • You are missing the point, `disabled` element do not trigger events. Test it yourself http://jsfiddle.net/ym34ud8j/ – Satpal Apr 28 '15 at 08:26
  • you should check this question, http://stackoverflow.com/questions/3100319/event-on-a-disabled-input – Robin Apr 28 '15 at 08:27

2 Answers2

4

I've made a Fiddle

Here's the code:

HTML

<form id="payment-form" action="chargeCard.php" method="POST" name="payment-form">
<input type="checkbox" id="terms" />
<input type="button"  id="customButton" value="submit" alt="button" class="disabled"/>
</form>

JS

$('#terms').on('change', function(){
if ($(this).is(':checked')){
    $('#customButton').removeClass('disabled');
}
else{
    $('#customButton').addClass('disabled');
}
});

$('#customButton').on('click',function(e){
if( $(this).hasClass('disabled') ){
    e.preventDefault();
    alert('Please confirm . . .');
}else{
    alert('go ahead...');
};
});

The long and short of it is, if an element is 'disabled' all events that happen on it are suppressed. In my fiddle I've 'faked' a disabled button using a style so the click event is still visible to the browser.

Pat Dobson
  • 3,249
  • 2
  • 19
  • 32
1
$("#customButton").click(function(){
if !($("#terms").is(':checked'))
 {
 alert("Accept terms first!");
 }
})

if your browser can not detect click on a disabled button, Warp the button inside a div and change the function to click on that div.

Ali Sheikhpour
  • 10,475
  • 5
  • 41
  • 82