1

I have a button that clears a list, the click on this button shows a dialog that asks for validation (Yes/No). What I want is to disable the "Clear" button after clearing the list (Click on Yes). Here's my code :

$('#clearBtn').click(function() {
    $('#alert5').show();
    $('#bg').show();
    $('#Yes').click(function(){
        $('.list1').empty();
        $('#clearBtn').disable(true);
        $('#clearBtn').click(function(e){
            e.preventDefault();
        });

        $(".alert").fadeOut(250);
        $(".alertbg").fadeOut(250);
    });
}); 

the preventDefault() function doesn't seem to work.

AymanKun
  • 241
  • 1
  • 4
  • 20

3 Answers3

5

First never nest event handlers.

$('#cleatBtn').click(function () {
    $('#alert5').show();
    $('#bg').show();
});

$('#Yes').click(function () {
    $('.list1').empty();
    $('#cleatBtn').attr('disabled', true);
    $(".alert").fadeOut(250);
    $(".alertbg").fadeOut(250);
});

If you just want to disable then use the following syntax

 $('#cleatBtn').attr('disabled', true);

Remove the innermost event completely.. That is not required.

Use on to bind the events, if you want the button to be enabled but turn off the event handler using off

One more option you have is to apply a class to the button when you press yes and execute the code only when the class is not present.

 $('#cleatBtn').click(function () {
       if( !$(this).hasClass('active')) {
           $('#alert5').show();
           $('#bg').show();
        }
    });

    $('#Yes').click(function () {
        $('.list1').empty();
        $('#cleatBtn').attr('disabled', true);
        $('#cleatBtn').addClass('active');
        $(".alert").fadeOut(250);
        $(".alertbg").fadeOut(250);
    });
Sushanth --
  • 55,259
  • 9
  • 66
  • 105
  • I should've mentioned that I want to override the style of the disabled button too. Is it possible to do that using toggleClass('.DisabledBtnStyle') ?? – AymanKun Dec 09 '13 at 23:34
0

To disable a button, call the prop function with the argument true on it:

$('#cleatBtn').prop("disabled", true);
Marius Schulz
  • 15,976
  • 12
  • 63
  • 97
0

e.preventDefault(); is the correct way of cancelling events. Some older browsers also expect a return type of false. Which I think will cause jQuery to call preventDefault()?

Here's a good answer: What's the effect of adding 'return false' to a click event listener?

I think your structure looks a bit odd. you don't need to attach click events within a click event.

Just attach them all separately on document.ready events. At the moment they are nested, then go back to trying to cancel your event. The dom tree might be confused by the way the events are nested.

Hope that helps.

Community
  • 1
  • 1
Captain John
  • 1,859
  • 2
  • 16
  • 30