jQuery 仅在填写所有字段时启用提交按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27829051/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:27:13  来源:igfitidea点击:

Enable submit button only when all fields are filled

jqueryhtmlforms

提问by Henrik Petterson

In my form, I want to enable form only when all fields (and radio button list) has been selected.

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

So far, I have successfully made the submit button enablewhen the titlefield has content with:

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

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

My aim is to enable submit button only once everythinghas been filled. How do I do this?

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

Here is my full code with working jsfiddle:

这是我使用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>

回答by eg_dac

Here is a fiddle for you. http://jsfiddle.net/soyn0xag/6/

这是给你的小提琴。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");
    }
});

回答by Sanova

use the "required" command inside the tag.

在标签内使用“required”命令。

edit: Even with the radio buttons. you'd only have to select one. Here is the JSFiddle: http://jsfiddle.net/soyn0xag/3/

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

edit 2: Added a new working JSfiddle with your request to keep the submit button disabled until all fields have content. I used jquery, and the submit button is available after all typable fields have content, and the radio buttons are still required with that nice pop up: http://jsfiddle.net/soyn0xag/9/

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

this option DISABLES the button again once you take away the content from one of the fields. I believe this is what you want.

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

edit 3 - Final FixFixed a bug that let the submit button show up early: http://jsfiddle.net/soyn0xag/36/

编辑 3 - 最终修复修复了一个让提交按钮提前显示的错误:http: //jsfiddle.net/soyn0xag/36/

As long as the and the submit button are wrapped in the same tag, you will not be able to submit without content in the now required input fields.

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

Example:

例子:

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

Note that required does not use quotes or any other delimiter.

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

回答by AstroCB

There are a few different ways to go about this (as you've likely seen above).

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

This probably isn't the most efficient way, but you could check every time they click or press a key to see if any of the text fields are empty and if any of the radio buttons are filled. If one radio button is filled and none of the text fields are empty, you can go ahead and enable the button. Otherwise, you can disable it (or leave it disabled).

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

Let's go line by line:

让我们一行一行地进行:

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

演示

回答by Master Slave

yet another solution

另一个解决方案

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/

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

回答by MD Ashik

I thing still have to give a answer for this Question: Live Demo Link

我还是要回答这个问题: 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>