woggles
woggles

Reputation: 7444

Adding a jquery click function to a disabled button?

How can I do this?

I have a disabled jquery ui button that I want to display an alert. The button becomes enabled when changing a dropdown on the page.

HTML:

<button id="AssignRolesButton" disabled="disabled">Assign Roles</button>

JS:

$(function () {    
    $('#AssignRolesButton').button();

    //doesnt work
    $('#AssignRolesButton').button().click(function (e) { e.preventDefault(); alert('yoyo'); }); 

    $('#ApplicationsDropdownList').change(function () {  
        //enables the button 
        $('#AssignRolesButton').removeAttr('disabled').removeClass('ui-state-disabled');
        //doesnt work
        $('#AssignRolesButton').button().click(function (e) { e.preventDefault(); alert('yoyo'); });
        // also doesnt work
        $('#AssignRolesButton').click(function (e) { e.preventDefault(); alert('yoyo'); });  
   });    
});

So to summarise, I need the button to have the jquery ui styling while disabled and register the click function when its enabled.

Upvotes: 0

Views: 178

Answers (3)

A. Wolff
A. Wolff

Reputation: 74420

Use a workaround as disabled elements don't fire attached event:

DEMO

$(function () {
    var $assignBtn = $('#AssignRolesButton');
    $('<div id="btn_overlay"/>').css({
        position: 'absolute',
        top: $assignBtn.offset().top,
        left: $assignBtn.offset().left,
        width: $assignBtn.outerWidth(),
        height: $assignBtn.outerHeight(),
        'z-index': 1000,
    }).click(function () {
        $assignBtn.triggerHandler('click');
    }).appendTo('body');

    $('#ApplicationsDropdownList').change(function () {
        $('#btn_overlay').remove();
        $assignBtn.prop('disabled', false);
        //...
    });
    $assignBtn.click(function (e) {
        e.preventDefault();
        alert('yoyo from btn handler');
    });
});

Upvotes: 1

Bergi
Bergi

Reputation: 665362

//enables the button 
$('#AssignRolesButton').removeAttr('disabled').removeClass('ui-state-disabled');

No. You will need to use the enable method of your Button-widget (Demo). Otherwise, the jQuery-UI-button is still disabled (even if it doesn't look like so) and jQueryUI intercepts the click event, stopping its propagation so that your handlers are not called. You can see this behavior clearly here - the handlers attached before jQueryUI's interceptor are still called.

e.preventDefault;

As others mentioned, this is a method and needs to be called: e.preventDefault();.

Upvotes: 1

Eric
Eric

Reputation: 18922

Then just bind the click event, when you have selected something in the dropdown. Otherwise, leave it un-touched.

Upvotes: 0

Related Questions