0

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?

2
  • You don't want to unbind actions right? So you can use the disabled property like $("#sub").prop("disabled",true); Commented Aug 12, 2013 at 11:47
  • is there a reason why you dont want to attach the event in the else? Commented Aug 12, 2013 at 11:50

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.