简体   繁体   English

禁用提交按钮,直到所有表单输入都有数据

[英]Disable submit button until all form inputs have data

I'm trying to disable the submit button until all inputs have some data. 我正在尝试禁用提交按钮,直到所有输入都有一些数据。 Right now the button is disabled, but it stays disabled after all inputs are filled in. What am I doing wrong? 现在按钮被禁用,但在填写完所有输入后它仍处于禁用状态。我做错了什么?

$(document).ready(function (){
    validate();
    $('input').on('keyup', validate);
});

function validate(){
    if ($('input').val().length > 0) {
        $("input[type=submit]").prop("disabled", false);
    } else {
        $("input[type=submit]").prop("disabled", true);
    }
} 

Here's a modification of your code that checks all the <input> fields, instead of just the first one. 这是对代码的修改,它检查所有<input>字段,而不仅仅是第一个字段。

 $(document).ready(function() { validate(); $('input').on('keyup', validate); }); function validate() { var inputsWithValues = 0; // get all input fields except for type='submit' var myInputs = $("input:not([type='submit'])"); myInputs.each(function(e) { // if it has a value, increment the counter if ($(this).val()) { inputsWithValues += 1; } }); if (inputsWithValues == myInputs.length) { $("input[type=submit]").prop("disabled", false); } else { $("input[type=submit]").prop("disabled", true); } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="text"><br> <input type="text"><br> <input type="text"><br> <input type="submit" value="Join"> 

Vanilla JS Solution. 香草JS解决方案。

In question selected JavaScript tag. 有问题选择JavaScript标记。

HTML Form: HTML表格:

<form action="/signup">
    <div>
        <label for="username">User Name</label>
        <input type="text" name="username" required/>
    </div>
    <div>
        <label for="password">Password</label>
        <input type="password" name="password" />
    </div>
    <div>
        <label for="r_password">Retype Password</label>
        <input type="password" name="r_password" />
    </div>
    <div>
        <label for="email">Email</label>
        <input type="text" name="email" />
    </div>
    <input type="submit" value="Signup" disabled="disabled" />
</form>

JavaScript: JavaScript的:

var form = document.querySelector('form')
var inputs = document.querySelectorAll('input')
var required_inputs = document.querySelectorAll('input[required]')
var register = document.querySelector('input[type="submit"]')
form.addEventListener('keyup', function(e) {
    var disabled = false
    inputs.forEach(function(input, index) {
        if (input.value === '' || !input.value.replace(/\s/g, '').length) {
            disabled = true
        }
    })
    if (disabled) {
        register.setAttribute('disabled', 'disabled')
    } else {
        register.removeAttribute('disabled')
    }
})

Some explanation: 一些解释:

In this code we add keyup event on html form and on every keypress check all input fields. 在此代码中,我们在html表单上添加keyup事件 ,并在每个按键上检查所有输入字段。 If at least one input field we have are empty or contains only space characters then we assign the true value to disabled variable and disable submit button. 如果我们至少有一个输入字段为空或仅包含空格字符,那么我们将true值分配给disabled变量并禁用submit按钮。

If you need to disable submit button until all required input fields are filled in - replace: 如果您需要禁用提交按钮,直到填写所有必需的输入字段 - 替换:

inputs.forEach(function(input, index) {

with: 有:

required_inputs.forEach(function(input, index) {

where required_inputs is already declared array containing only required input fields. 其中required_inputs已被声明为仅包含必需输入字段的数组。

JSFiddle Demo: https://jsfiddle.net/ydo7L3m7/ JSFiddle演示: https ://jsfiddle.net/ydo7L3m7/

You could try using jQuery Validate 您可以尝试使用jQuery Validate

http://jqueryvalidation.org/ http://jqueryvalidation.org/

<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.js"></script>

And then do something like the following: 然后执行以下操作:

$('#YourFormName').validate({
    rules: {
        InputName1: {
            required: true
        },
        InputName2: { //etc..
            required: true
        }
    }
});

Refer to the sample here . 请参阅此处的示例。

In this only input of type="text" has been considered as described in your question. 在这个问题中,只考虑了type="text" input

HTML: HTML:

<div>
    <form>
        <div>
            <label>
                Name:
                <input type="text" name="name">
            </label>
        </div>
        <br>
        <div>
            <label>
                Age:
                <input type="text" name="age">
            </label>
        </div>
        <br>
        <div>
            <input type="submit" value="Submit">
        </div>
    </form>
</div>

JS: JS:

$(document).ready(function () {
    validate();
    $('input').on('keyup check', validate);
});

function validate() {
    var input = $('input');
    var isValid = false;
    $.each(input, function (k, v) {
        if (v.type != "submit") {
            isValid = (k == 0) ?
              v.value ? true : false : isValid && v.value ? true : false;
        }
        if (isValid) {
            $("input[type=submit]").prop("disabled", false);
        } else {
            $("input[type=submit]").prop("disabled", true);
        }
    });
}

Try to modify your function like this : 尝试像这样修改你的功能:

function validate(){
    if ($('input').val() != '') {
        $("input[type=submit]").prop("disabled", false);
    } else {
        $("input[type=submit]").prop("disabled", true);
    }
} 

and place some event trigger or something like onkeyup in jquery.But for plain js, it looks like this : 并在jquery中放置一些事件触发器或类似onkeyup的东西。对于普通的js,它看起来像这样:

<input type = "text" name = "test" id = "test" onkeyup = "validate();">

Not so sure of this but it might help. 不太确定这一点,但它可能有所帮助。

Here is a dynamic code that check all inputs to have data when wants to submit it: 这是一个动态代码,在想要提交数据时检查所有输入以获取数据:

  $("form").submit(function(e) { var error = 0; $('input').removeClass('error'); $('.require').each(function(index) { if ($(this).val() == '' || $(this).val() == ' ') { $(this).addClass('error'); error++; } }); if (error > 0) { //Means if has error: e.preventDefault(); return false; } else { return true; } }); 
 .error { border: 1px solid red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <form> <form action="google.com"> <input type="text" placeholder="This is input #1" class="require" /> <input type="text" placeholder="This is input #2" class="require" /> <input type="submit" value="submit" /> </form> </form> 

Now you see there is a class called require , you just need to give this class to inputs that have to have value then this function will check if that input has value or not, and if those required inputs are empty Jquery will prevent to submit the form! 现在您看到有一个名为require的类,您只需要将此类赋予必须具有值的inputs ,然后此函数将检查该输入是否具有值,如果这些必需输入为空,则Jquery将阻止提交形成!

Modify your code 修改你的代码

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script>
    <input type="text"><br>
    <input type="text"><br>
    <input type="text"><br>
    <input type="submit" value="Join">

    <script>
    $(document).ready(function (){
        validate();
        $('input').on('keyup', validate);
    });

    function validate(){

        $("input[type=text]").each(function(){
            if($(this).val().length > 0)
            {
                $("input[type=submit]").prop("disabled", false);
            }
            else
            {
                $("input[type=submit]").prop("disabled", true);
            }
        });
    } 
    </script>

 function disabledBtn(_className,_btnName) { var inputsWithValues = 0; var _f = document.getElementsByClassName(_className); for(var i=0; i < _f.length; i++) { if (_f[i].value) { inputsWithValues += 1; } } if (inputsWithValues == _f.length) { document.getElementsByName(_btnName)[0].disabled = false; } else { document.getElementsByName(_btnName)[0].disabled = true; } } 
 <input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br> <input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br> <input type="text" class="xxxxx" onKeyUp="disabledBtn('xxxxx','fruit')"><br> <input type="submit" value="Join" id="yyyyy" disabled name="fruit"> 

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

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