7

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

2
  • Phill, Did you work this out in the end? Are you able to provide your final solution? Commented Dec 16, 2010 at 4:15
  • @blairyeah - check out the answer by Michael Irgoyen Commented Mar 7, 2012 at 12:20

4 Answers 4

35

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.

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

5 Comments

@PhillPafford - Isn't this the correct solution? It worked flawlessly for me.
This is by far the best approach I've ever seen for doing validations!
spent more than 30 hrs figuring out a solution for this type of validation, Thank you.
Shouldn't there be a comma between 'change' and 'keyup'? Anyways, this isn't working for me for some reason. The submit button never gets disabled.
Doesn't work for me. Button does not get disabled and disabled class does not get added.
1

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!

3 Comments

Here is a callback for the Validation plug-in docs.jquery.com/Plugins/Validation/Methods/required
Hmm I see what you're trying to do but it's not working with what I have. I think I need to incorporate the validation plug-in
what about some sort of focus event?
0

A more elegant and fast solution is to simply override the default on-click and on-keyup events adding the code you need as follows instead of adding another listen event

$("#form").validate({
    submitHandler: function(form) {
        form.submit();
    },
    onkeyup: function( element, event ) {
        if ( event.which === 9 && this.elementValue(element) === "" ) {
            return;
        } else if ( element.name in this.submitted || element === this.lastElement ) {
            this.element(element);
        }

        if (this.checkForm()) { // checks form for validity
            $('a.submit').attr('class', 'submit btn btn-success');        // enables button
        } else {
            $('a.submit').attr('class', 'submit btn btn-danger disabled');   // disables button
        }
    },
    onclick: function( element ) {
        // click on selects, radiobuttons and checkboxes
        if ( element.name in this.submitted ) {
            this.element(element);

        // or option elements, check parent select in that case
        } else if ( element.parentNode.name in this.submitted ) {
            this.element(element.parentNode);
        }

        if (this.checkForm()) { // checks form for validity
            $('a.submit').attr('class', 'submit btn btn-success');        // enables button
        } else {
            $('a.submit').attr('class', 'submit btn btn-danger disabled');   // disables button
        }
    }
})

With the following css code for the submit trigger - initially disabled (bootstrap 3 classes):

<a onclick="if(!$(this).hasClass('disabled')) { $('#form').submit(); }" class="submit btn btn-danger disabled">button_save</a>

This can very easy be used with jquery plug-in areYouSure to only enable the submit when actual changes are made:

if (this.checkForm() && $('#form').hasClass('dirty')) { // checks form for validity

initializing the plug-in using silent:

$('#form').areYouSure( {'silent':true} );

Comments

-2

I've used the validation plugin before but I can't remember all the details. I'm pretty sure it's something like this:

$(function() {
    $('#myForm').validate(
        rules: {
            'elementToWatch': {
                success: function(element) { 
                    if($("#myform").validate().element("#myselect")) {
                        $('#chargeamtaddButton:disabled').removeAttr('disabled');
                    } else {
                        $('#chargeamtaddButton').attr('disabled','disabled');
                    }
                },
                // etc...
             },
             // etc...
         },
         // etc...
     });
 });

Since there are so many ways to use the validation plugin, it's hard to give you perfect advice but I hope what I've shown gives you a better idea of how to move forward. Maybe if you gave some more code and HTML, I could help you out more.

5 Comments

man this is so close I just can't get it, does the success need to be outside of the rules?
what about some sort of focus event?
This doesn't work. The success method cannot be under the rules method. Also, the success method only begins firing after the form has been submitted for the first time. It also is fired anytime anything on the form is changed, meaning it will return true if the specific field you're on validates, even if other fields on your form do not. This is meant for changed the current fields label or adding a message about the current field. A simple read in the manual would have explained this behavior. docs.jquery.com/Plugins/Validation/validate
@PhillPafford - wait, why is this accepted then if it doesn't work?
@ripper234 this answer probably led me to the solution I was searching for at the time

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.