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

前端 未结 4 1555
孤街浪徒
孤街浪徒 2020-12-02 19:55

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.

4条回答
  •  心在旅途
    2020-12-02 20:18

    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):

    button_save
    

    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} );
    

提交回复
热议问题