views:

90

answers:

2

Hello, I was wondering how you can disable button (not submit) with jQuery while a form doesn't validate with jQuery validate, but when it does validate, enabled the button.

A: 
$('#button').attr('disabled', 'disabled');
$("#myform").validate();
$("#submit").click(function() {
    if ($("#myform").valid())
        $('#button').removeAttr('disabled');
});
Scott Evernden
thanks! I actually binded it to the blur method, it works just as well, except it doesn't require an extra button!
Kyle
A: 

That's a little tricky to do. What I'd suggest trying is binding an change() event:

$(":input").change(function() {
  $('#formid").validate();
  if ($("#formid").valid()) {
    $("#buttonid").removeAttr("disabled");
  } else {
    $("#buttonid").attr("disabled", true);
  }
});

The weakness of this method is that, for example, if a text field can't be blank the change() event won't be fired until it loses focus so the button won't be ungreyed. If this is important to you you could add a keydown() event.

cletus
Small typo - I think line 5 should be '...removeAttr...". Also, if there is any change that you will add input fields dynamically, you can use the jquery "live" method rather than "change" to attach a listner to all input fields, even ones added after the page loads.
Ed Schembor