【问题标题】:Enable submit button only when all fields are filled仅在填写所有字段时启用提交按钮
【发布时间】:2015-01-07 21:35:22
【问题描述】:

在我的表单中,我只想在所有字段(和单选按钮列表)都被选中时启用表单。

到目前为止,当title 字段包含以下内容时,我已经成功制作了提交按钮enable:

onkeyup="if(this.textLength != 0) {subnewtopic.disabled = false} else {subnewtopic.disabled = true}"

我的目标是仅在 所有内容 填写完毕后启用提交按钮。我该怎么做?

这是我使用jsfiddle的完整代码:

            <form action="" method="post" id="subnewtopicform" />

                Title:
                <input type="text" name="title" onkeyup="if(this.textLength != 0) {subnewtopic.disabled = false} else {subnewtopic.disabled = true}">

<br/>

                Description:
                <textarea name="description"></textarea> 

<br/>
                Category:
<ul class="list:category categorychecklist form-no-clear" id="categorychecklist">

<li id="category-19"><label class="selectit"><input type="radio" id="in-category-19" name="category" value="19"> Animation</label></li>

<li id="category-20"><label class="selectit"><input type="radio" id="in-category-20" name="category" value="20"> Anime</label></li>

    </ul>

                <input type="submit" value="Submit Topic" class="button-primary" name="subnewtopic" id="subnewtopic" disabled="disabled" /> 

            </form>

【问题讨论】:

  • 看来你真的是在找人为你写验证码。有很多插件和教程。您过于简单的代码距离成为表单验证器还有很长的路要走。您还可以访问 html5 有效性属性。老实说,你应该做更多的研究

标签: jquery html forms


【解决方案1】:

这是给你的小提琴。 http://jsfiddle.net/soyn0xag/6/

$("input[type='text'], textarea").on("keyup", function(){
    if($(this).val() != "" && $("textarea").val() != "" && $("input[name='category']").is(":checked") == true){
        $("input[type='submit']").removeAttr("disabled");
    } else {
        $("input[type='submit']").attr("disabled", "disabled");
    }
});

$("input[name='category']").on("change", function(){
    if($(this).val() != "" && $("textarea").val() != "" && $("input[name='category']").is(":checked") == true){
        $("input[type='submit']").removeAttr("disabled");
    } else {
        $("input[type='submit']").attr("disabled", "disabled");
    }
});

【讨论】:

  • 这应该可以帮助您入门。如果有人清空盒子,您可以添加一个 else 并再次禁用该按钮。
  • 太棒了!如果字段为空,您能否告诉我如何再次禁用该按钮?
【解决方案2】:

使用标签内的“必需”命令。

编辑:即使是单选按钮。你只需要选择一个。这是JSFiddle: http://jsfiddle.net/soyn0xag/3/

编辑 2:添加了一个新的工作 JSfiddle,您的请求保持禁用提交按钮,直到所有字段都有内容。我使用了 jquery,并且在所有可键入的字段都有内容之后,提交按钮才可用,并且在那个漂亮的弹出窗口中仍然需要单选按钮: http://jsfiddle.net/soyn0xag/9/

一旦您从其中一个字段中删除内容,此选项将再次禁用该按钮。我相信这就是你想要的。

edit 3 - Final Fix 修复了让提交按钮提前显示的错误: http://jsfiddle.net/soyn0xag/36/

只要和提交按钮被包裹在同一个标​​签中,您将无法在现在需要的输入字段中没有内容的情况下提交。

例子:

<input type="radio" id="in-category-19" name="category" value="19" required> Animation</label>

请注意,required 不使用引号或任何其他分隔符。

【讨论】:

  • 但是使用这种方法...所有单选按钮都需要按下这是不可能的,因为只能点击其中一个...=
  • 不正确@HenrikPetterson,因为它是一个单选按钮,您只需选择一个:查看此更新的小提琴:jsfiddle.net/soyn0xag/3
  • 有趣,但有什么方法可以让提交按钮保持禁用状态,直到所有字段都有内容?
  • @HenrikPetterson 是的,看看这个更新的 jsfiddle:jsfiddle.net/soyn0xag/9 我也用这个链接更新了我的答案。
  • 哇,太好了,不过它有一个问题。如果您先填写说明框,则提交按钮将变为启用状态,即使标题框已清空。
【解决方案3】:

另一种解决方案

required = function(fields) {
  var valid = true;
  fields.each(function () { // iterate all
    var $this = $(this);
    if (($this.is(':checkbox') && !$this.is(":checked")) || // checkbox
       (($this.is(':text') || $this.is('textarea')) && !$this.val()) || // text 
       ($this.is(':radio') && !$('input[name='+ $this.attr("name") +']:checked').length)) {
            valid = false;
        }
    });
    return valid;
}

validateRealTime = function () {
    var fields = $("form :input:not(:hidden)"); // select required
    fields.on('keyup change keypress blur', function () {
        if (required(fields)) {
            {subnewtopic.disabled = false} // action if all valid
        } else {
            {subnewtopic.disabled = true} // action if not valid
        }
    });
}

http://jsfiddle.net/jsq7m8hL/2/

【讨论】:

    【解决方案4】:

    有几种不同的方法可以解决这个问题(正如您在上面可能看到的那样)。

    这可能不是最有效的方法,但您可以检查他们每次单击或按下某个键时是否有任何文本字段为空以及是否已填充任何单选按钮。如果一个单选按钮被填满并且没有一个文本字段为空,您可以继续启用该按钮。否则,您可以禁用它(或保持禁用状态)。

    让我们逐行进行:

    function check() { // Define a function that we can call our event listeners with
        // Get our inputs and textareas
        var inputs = document.getElementsByTagName("input");
        var textareas = document.getElementsByTagName("textarea");
        var filled = true; // We'll assume that all of the fields are full unless proven otherwise
        var oneChecked = false; // We can use this to keep track of the radio buttons (by assuming at first that none are checked)
    
        for (var i = 0; i < inputs.length; i++) { // Loop through all of the inputs first
            if (inputs[i].type === "text" && !inputs[i].value) { // If the input is a text field, check whether it is empty; if so, set filled to false
                filled = false;
            }
    
            if (inputs[i].type === "radio" && inputs[i].checked) { // If the input is a radio button, see if it is filled in; because we only need one radio button to be filled in, that's all we need to know
                oneChecked = true;
            }
    
        }
    
        if (!oneChecked) { // Check outside of the loop if any of our radio buttons were selected and, if not, set filled to false
            filled = false;
        }
    
        for (var j = 0; j < textareas.length; j++) { // Now loop through all of the text areas; if any aren't filled in, set filled to false
            if (!textareas[j].value) {
                filled = false;
            }
        }
    
        if (filled) { // Check whether any of the fields are empty (or, in the radio button's case, if one is selected, and enable/disable the button accordingly
            document.getElementById("subnewtopic").disabled = false;
        } else {
            document.getElementById("subnewtopic").disabled = true;
        }
    }
    
    // Add event listeners to check for keypresses and clicks
    window.addEventListener("keyup", check);
    window.addEventListener("click", check);
    

    Demo

    【讨论】:

    • 嗨 AstroCB,我真的很喜欢你对这个主题的解决方案!我举了你的例子并添加了多个复选框并选择选项。我可以让多个复选框与提交按钮一起使用,但是,我卡在选择选项上,这不适用于提交按钮。请在jsfiddle.net/0oprsc4j/6 中查看此示例,请帮帮我。谢谢。
    【解决方案5】:

    我还是要回答这个问题: Live Demo Link

    $(document).on('change keyup', '.required', function(e){
       let Disabled = true;
        $(".required").each(function() {
          let value = this.value
          if ((value)&&(value.trim() !=''))
              {
                Disabled = false
              }else{
                Disabled = true
                return false
              }
        });
    
       if(Disabled){
            $('.toggle-disabled').prop("disabled", true);
          }else{
            $('.toggle-disabled').prop("disabled", false);
          }
     })
    

     $(document).on('change keyup', '.required', function(e){
       let Disabled = true;
        $(".required").each(function() {
          let value = this.value
          if ((value)&&(value.trim() !=''))
              {
                Disabled = false
              }else{
                Disabled = true
                return false
              }
        });
       
       if(Disabled){
            $('.toggle-disabled').prop("disabled", true);
          }else{
            $('.toggle-disabled').prop("disabled", false);
          }
     })
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <select class="required">
        <option value="" selected disabled>selected a value</option>
        <option>Car</option>
        <option>Buss</option>
        <option>Train</option>
    </select>
     
    <select class="required">
        <option value="" selected  disabled>selected a option</option>
        <option>A</option>
        <option>B</option>
        <option>C</option>
        <option>D</option>
    </select>
    <br /> <br /> 
    <input type="text" class="required" placeholder="Full Name">
    
    <input type="number" class="required" placeholder="Age">
    <br /> <br /> 
    <button type="button" class="toggle-disabled" disabled>Submit</button>

    【讨论】:

      猜你喜欢
      • 2017-10-25
      • 1970-01-01
      • 2015-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-15
      相关资源
      最近更新 更多