简体   繁体   English

检查空白字段并禁用按钮

[英]Checking for empty fields and disabling button

I'm checking for three text fields, and if empty, the submit button should not be clickable. 我正在检查三个文本字段,如果为空,则不应单击“提交”按钮。 If all three text fields are not empty, then (as you guessed) the submit button will be clickable. 如果所有三个文本字段都不为空,那么(您猜到了)提交按钮将是可单击的。

//nameText, emailText, commentsText = text fields
//If fields are non-empty, disabled status = false
$(nameText, emailText, commentsText).each(function() {
    if ($(this).val() != "") {
        $('#submitButton').prop('disabled', false);
    }
});

//If fields are empty, disabled status = true
$(nameText, emailText, commentsText).each(function() {
    if ($(this).val() == "") {
        $('#submitButton').prop('disabled', true);
    }
});

This isn't exactly working. 这不完全有效。 The button is constantly disabled, and doesn't get enabled even when the fields are filled. 该按钮一直处于禁用状态,即使填充了字段也不会启用。 Can someone point out what I'm doing wrong? 有人可以指出我做错了吗? Thank you. 谢谢。

You're missing a parenthesis: 您缺少括号:

if $(this).val() == "") {

should read: 应该读:

if ($(this).val() == "") {

This is the case for both of your conditions. 这两种情况都是如此。

I'd also use a flag so that you only need to use the one loop: 我还将使用一个标志,以便您只需要使用一个循环:

var isValid = true;

$(nameText, emailText, commentsText).each(function() {
    if ($(this).val() == "")
        isValid = false;
});

$('#submitButton').prop('disabled', !isValid);

You could check it using: 您可以使用以下方法进行检查:

$('#submitButton').prop('disabled', function(){
    return !!$(nameText).add(emailText).add(commentsText).filter(function(){
       return !this.value.trim(); 
    }).length
});

May be you can take a look at this code snippet. 也许您可以看一下此代码段。

 $(document).ready(function(){ checkFormValidity(); $("#name,#email,#comment ").keyup(function(){ checkFormValidity(); }); function checkFormValidity(){ var allFilled = true; $("#name,#email,#comment").each(function() { if ($(this).val() == "") { allFilled = false; } }); $('#submitButton').prop('disabled', (!allFilled)); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <form > <fieldset> <legend>Personal information:</legend> Name:<br> <input type="text" id="name" name="Name" value=""> <br> Email:<br> <input type="text" id="email" name="email" value=""> <br> Comments:<br> <input type="text" id="comment" name="comment" value=""> <br><br> <input type="submit" id="submitButton" value="Submit"> </fieldset> </form> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM