Disabling submit button until all fields have values

拟墨画扇 提交于 2019-11-26 11:13:24
Hristo

Check out this jsfiddle.

HTML

// note the change... I set the disabled property right away
<input type="submit" id="register" value="Register" disabled="disabled" />

JavaScript

(function() {
    $('form > input').keyup(function() {

        var empty = false;
        $('form > input').each(function() {
            if ($(this).val() == '') {
                empty = true;
            }
        });

        if (empty) {
            $('#register').attr('disabled', 'disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
        } else {
            $('#register').removeAttr('disabled'); // updated according to http://stackoverflow.com/questions/7637790/how-to-remove-disabled-attribute-with-jquery-ie
        }
    });
})()

The nice thing about this is that it doesn't matter how many input fields you have in your form, it will always keep the button disabled if there is at least 1 that is empty. It also checks emptiness on the .keyup() which I think makes it more convenient for usability.

$('#user_input, #pass_input, #v_pass_input, #email').bind('keyup', function() {
    if(allFilled()) $('#register').removeAttr('disabled');
});

function allFilled() {
    var filled = true;
    $('body input').each(function() {
        if($(this).val() == '') filled = false;
    });
    return filled;
}

JSFiddle with your code, works :)

For all solutions instead of ".keyup" ".change" should be used or else the submit button wont be disabled when someone just selects data stored in cookies for any of the text fields.

Hussein

All variables are cached so the loop and keyup event doesn't have to create a jQuery object everytime it runs.

var $input = $('input:text'),
    $register = $('#register');    
$register.attr('disabled', true);

$input.keyup(function() {
    var trigger = false;
    $input.each(function() {
        if (!$(this).val()) {
            trigger = true;
        }
    });
    trigger ? $register.attr('disabled', true) : $register.removeAttr('disabled');
});

Check working example at http://jsfiddle.net/DKNhx/3/

DEMO: http://jsfiddle.net/kF2uK/2/

function buttonState(){
    $("input").each(function(){
        $('#register').attr('disabled', 'disabled');
        if($(this).val() == "" ) return false;
        $('#register').attr('disabled', '');
    })
}

$(function(){
    $('#register').attr('disabled', 'disabled');
    $('input').change(buttonState);
})

Grave digging... I like a different approach:

elem = $('form')
elem.on('keyup','input', checkStatus)
elem.on('change', 'select', checkStatus)

checkStatus = (e) =>
  elems = $('form').find('input:enabled').not('input[type=hidden]').map(-> $(this).val())
  filled = $.grep(elems, (n) -> n)
  bool = elems.size() != $(filled).size()
  $('input:submit').attr('disabled', bool)

I refactored the chosen answer here and improved on it. The chosen answer only works assuming you have one form per page. I solved this for multiple forms on same page (in my case I have 2 modals on same page) and my solution only checks for values on required fields. My solution gracefully degrades if JavaScript is disabled and includes a slick CSS button fade transition.

See working JS fiddle example: https://jsfiddle.net/bno08c44/4/

JS

$(function(){
 function submitState(el) {

    var $form = $(el),
        $requiredInputs = $form.find('input:required'),
        $submit = $form.find('input[type="submit"]');

    $submit.attr('disabled', 'disabled');

    $requiredInputs.keyup(function () {

      $form.data('empty', 'false');

      $requiredInputs.each(function() {
        if ($(this).val() === '') {
          $form.data('empty', 'true');
        }
      });

      if ($form.data('empty') === 'true') {
        $submit.attr('disabled', 'disabled').attr('title', 'fill in all required fields');
      } else {
        $submit.removeAttr('disabled').attr('title', 'click to submit');
      }
    });
  }

  // apply to each form element individually
  submitState('#sign_up_user');
  submitState('#login_user');
});

CSS

input[type="submit"] {
  background: #5cb85c;
  color: #fff;
  transition: background 600ms;
  cursor: pointer;
}

input[type="submit"]:disabled {
  background: #555;
  cursor: not-allowed;
}

HTML

<h4>Sign Up</h4>
<form id="sign_up_user" data-empty="" action="#" method="post">
 <input type="email" name="email" placeholder="Email" required>
 <input type="password" name="password" placeholder="Password" required>
 <input type="password" name="password_confirmation" placeholder="Password Confirmation" required>
 <input type="hidden" name="secret" value="secret">
 <input type="submit" value="signup">
</form>

<h4>Login</h4>
<form id="login_user" data-empty="" action="#" method="post">
 <input type="email" name="email" placeholder="Email" required>
 <input type="password" name="password" placeholder="Password" required>
 <input type="checkbox" name="remember" value="1"> remember me
 <input type="submit" value="signup">
</form>

Built upon rsplak's answer. It uses jQuery's newer .on() instead of the deprecated .bind(). In addition to input, it will also work for select and other html elements. It will also disable the submit button if one of the fields becomes blank again.

var fields = "#user_input, #pass_input, #v_pass_input, #email";

$(fields).on('change', function() {
    if (allFilled()) {
        $('#register').removeAttr('disabled');
    } else {
        $('#register').attr('disabled', 'disabled');
    }
});

function allFilled() {
    var filled = true;
    $(fields).each(function() {
        if ($(this).val() == '') {
            filled = false;
        }
    });
    return filled;
}

Demo: JSFiddle

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!