Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery disable button (NOT Submit) until field validates + Validation Plugin

Tags:

jquery

I have 4 buttons on my form, a Submit, Cancel, Add and Remove button. All are working as expected but I would like to disable the Add button until the input field validates. I'm using the Validation plug-in and I think this can be done with a required validation with a callback but I'm not sure.

Could someone point me in the right direction?

UPDATE:

Here is an idea of some code

required: function(element) { 
   return($('#chargeamtaddButton').attr('disabled', ? '','disabled');
}

Looking for that true/false option flag to set the disabled attribute

like image 467
Phill Pafford Avatar asked May 19 '09 12:05

Phill Pafford


2 Answers

I've actually discovered the best way to do this, and it's using an undocumented method checkForm() within the plugin.

Add this code to the $(document).ready() function on the page your form is on.

$('#yourform').bind('change keyup', function() {
    if($(this).validate().checkForm()) {
        $('#submitbutton').removeClass('button_disabled').attr('disabled', false);
    } else {
        $('#submitbutton').addClass('button_disabled').attr('disabled', true);
    }
});

In this case, it will add the class button_disabled to the button and then add the disabled attribute. You can apply a disabled style to the button via CSS.

like image 121
Michael Irigoyen Avatar answered Nov 11 '22 01:11

Michael Irigoyen


jQuery Validate Plugin Documentation: Form Method

The above method of the validate plugin allows you to check if a form is valid. So if you can't get the callback to work then I would run a timer and check to see if the form is valid every so often, and if so enable your button. This sucks though.

I can't find a success callback for the validation plug in, so I think you are stuck using the submitHandler method. However, you aren't actually ready to submit the form yet, as you still want to add fields. So my proposed solution is leaving the add button enabled all the time, but having it call a function when clicked to see if the form is valid. If so, then add your field or whatnot, and if not then pop up the errors. So:

<body onload="formValidator = $('#form').validate();">
...
<input value='add' name='add' onclick='addIsValid();'>
...
<script type='text/javascript' language='javascript'>
function addIsValid() {
   if(formValidator.numberOfInvalids() > 0) {
          formValidator.showErrors();
      } else {
          addElementToFormOrWhatever();
      } 
   }
</script>

Or at least something to that effect. Good luck!

like image 42
hornairs Avatar answered Nov 10 '22 23:11

hornairs