Or Weinberger
Or Weinberger

Reputation: 7482

Temporarily disable button using jQuery

I would like to disable a button element without removing the listener, for example I have ths following code:

<input id="in" />
<button id="sub">Submit</button>

$('#sub').click(function (e) {
    //Some actions
});


$($('#in').keyup(function (e) {
    if (new Date($(this).val()) == 'Invalid Date') {
        $(this).addClass('invalid');
        $('#sub').addClass('disabled');
    }
    else {
        $(this).removeClass('invalid');
        $('#sub').removeClass('disabled');

    }
});

I would like to unbind the button click listener, but if I'll use off() or unbind() I will have to 're-bind' it in the else clause.

Is there any better way of doing this?

Upvotes: 0

Views: 1897

Answers (2)

schnill
schnill

Reputation: 955

use $('#sub').prop('disabled');

Upvotes: 0

CodingIntrigue
CodingIntrigue

Reputation: 78595

How about disabling the button instead of adding a class?

HTML:

<button>Disable Me</button>

JS

$(function() {
    $("button").click(function() {
        alert("click!");
       $(this).prop("disabled", true); 
    });
});

CSS

button[disabled] {
 color: red;
}

Here is a jsFiddle to demonstrate.

Upvotes: 3

Related Questions