Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disabled button still listens to click event

I have a problem in a form where I do some jquery validations. If a specific input field is not filled out, it should disable a "step forward" button by adding a disabled attribute:

if errors
  $('.btn-move-forward').attr("disabled", true)

that works but I also have a click event on that button: (coffeescript)

$('.btn-move-forward').click ->
  $('#step2, #step3').toggle()

I expect .btn-move-forward to not fire the click event when the button is disabled but it does!!

First: I don't understand why because every browser spec defines that this should not happen. Anyways, I tried to bypass it by doing the following stuff:

$('.btn-move-forward').click ->
  if !$(this).is(:disabled)
    $('#step2, #step3').toggle()

or this

$('.btn-move-forward').click ->
  if $(this).prop("disabled", false)
    $('#step2, #step3').toggle()

or combining the event listeners like this:

$('.btn-move-forward').on 'click', '.btn-move-forward:enabled', ->
   $('#step2, #step3').toggle()

No, all of this won't work properly. The button still behaves as a move-forward button.

All I want is the button not listening to onclick if it is disabled.

like image 202
DonMB Avatar asked May 09 '16 07:05

DonMB


1 Answers

The disabled property only applies to form elements. This means that unless the .btn-move-forward element is a <button> or <input type="button"> then the disabled attribute will have no effect.

You can see a working example using a button here:

$('.btn-move-forward').prop("disabled", true).click(function() {
  console.log('Moving forward...');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button class="btn-move-forward">Move forward</button>
like image 156
Rory McCrossan Avatar answered Oct 04 '22 04:10

Rory McCrossan