Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To disable a send button if fields empty by jQuery

Tags:

jquery

button

How can you disable the send -button if there is one or more input -fields empty?

My attempt in pseudo-code

if ( $("input:empty") ) {
    $("input:disabled") 
}
else 
  // enable the ask_question -button

I have been reading these articles without finding a right solution

  1. Official docs about empty: this is like not relevant because it looks for all input -fields
  2. a thread about disabled -feature in jQuery: this seems to be relevant
  3. to be able to test jQuery Firefox/terminal: to get a testing environment would help me most

I use at the moment the following code. It contains one bug about the character ;, but I cannot find it.

#1

$(document).ready(function(){
    $("#ask_form").validate(){
        rules: {
            username {
                required: true,
                minlenghth: 2
            },
            email: {
                required: true;
                minlength: 6
            },
            password {
                required: true,                                                                                                                                    
                minlength: 6
            }
        } 
    });
}

#2 Meder's code

I slighhtly modified Meder's code. It disables the send -button permanently so it has a bug too.

$(document).ready(function(){
    var inputs = $('input', '#ask_form'), empty = false;
    // can also use :input but it will grab textarea/select elements and you need to check for those..

    inputs.each(function() {
        if ( $(this).val() == '' ) {
            empty = true;
            return;
        }
    });

    if ( empty ) {
        $('.ask_question').attr('disabled', 'disabled'); // or true I believe.
    }
});
like image 680
Léo Léopold Hertz 준영 Avatar asked Aug 27 '09 17:08

Léo Léopold Hertz 준영


1 Answers

var $submit = $("input[type=submit]");
if ( $("input:empty").length > 0 ) {
   $submit.attr("disabled","disabled");
} else {
   $submit.removeAttr("disabled");
}
like image 121
Jason Avatar answered Sep 23 '22 04:09

Jason