Javascript 强制用户在启用表单提交之前填写所有字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31762447/
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
Force user to fill all fields before enabling form submit
提问by Henrik Petterson
I have a form containing various fields.
我有一个包含各种字段的表单。
See jsFiddle demo.
参见jsFiddle 演示。
My aim is to enable the submit button only when the user has filled in all fields.
我的目标是仅在用户填写所有字段时启用提交按钮。
So far, I'm able to force the title field to have content before submit button is enabled. How do I make it so that all other fields need to be filled too beforesubmit button is enabled.
到目前为止,我能够在启用提交按钮之前强制标题字段包含内容。我如何做到这一点,以便在启用提交按钮之前也需要填写所有其他字段。
jQuery("input[type='text']").on("keyup", function () {
if (jQuery(this).val() != "" ) {
if (jQuery("#titlenewtide").val() != '')
{
jQuery("#subnewtide").removeAttr("disabled");
}
} else {
jQuery("#subnewtide").attr("disabled", "disabled");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post" id="new_tide">
Title: <input id="titlenewtide" type="text" name="title" required> <br>
Description: <textarea name="description" id="description"></textarea> <br>
Tag: <input id="newtag" type="text" name="newtag" required> <br>
Category: <input type="radio" name="category" value="19" required> Animation
<button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
</form>
Note that I am loading the JavaScripts in my footer.
请注意,我正在页脚中加载 JavaScript。
采纳答案by cн?dk
- Make the changes take effect after changing inputs values:
- 更改输入值后使更改生效:
On each input
change, test the values of other inputs
and checked state of radio
, if all inputs
has been entered it will make the submit button
enabled:
在每次input
更改时,测试 otherinputs
和已检查状态的值radio
,如果所有inputs
都已输入,它将button
启用提交:
var validateInputs = function validateInputs(inputs) {
var validForm = true;
inputs.each(function(index) {
var input = $(this);
if (!input.val() || (input.type === "radio" && !input.is(':checked'))) {
$("#subnewtide").attr("disabled", "disabled");
validForm = false;
}
});
return validForm;
}
inputs.change(function() {
if (validateInputs(inputs)) {
$("#subnewtide").removeAttr("disabled");
}
});
Demo:
演示:
var inputs = $("form#myForm input, form#myForm textarea");
var validateInputs = function validateInputs(inputs) {
var validForm = true;
inputs.each(function(index) {
var input = $(this);
if (!input.val() || (input.type === "radio" && !input.is(':checked'))) {
$("#subnewtide").attr("disabled", "disabled");
validForm = false;
}
});
return validForm;
}
inputs.change(function() {
if (validateInputs(inputs)) {
$("#subnewtide").removeAttr("disabled");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post" id="myForm">
Title:
<input id="titlenewtide" type="text" name="title" required>
<br>Description:
<textarea name="description" id="description"></textarea>
<br>Tag:
<input id="newtag" type="text" name="newtag" required>
<br>Category:
<input type="radio" name="category" value="19" required>Animation
<button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
</form>
Also it uses the form id="myForm"
, so you can use it to validate only specific forms in your pages.
它还使用 form id="myForm"
,因此您可以使用它来仅验证页面中的特定表单。
Note: This is tested and working on Chrome
, Firefox
and IE
.
注意:这是经过测试并在Chrome
,Firefox
和上工作的IE
。
EDIT:
编辑:
- Make the changes take effect when we type in the inputs:
- 当我们输入输入时使更改生效:
In the previous code we are using onchange
event handler to call the function so it's only called when we click outside a given input (after change).
在前面的代码中,我们使用onchange
事件处理程序来调用函数,因此只有在我们单击给定输入之外(更改后)时才会调用它。
To perform the call automatically when the user enters a character in a field (the last one) we need to use the onkeyup
event so we don't need to click outside of it.
要在用户在字段(最后一个)中输入字符时自动执行调用,我们需要使用该onkeyup
事件,因此我们不需要在它外部单击。
This is the changed code you need :
这是您需要的更改后的代码:
var inputs = $("form#myForm input, form#myForm textarea");
var validateInputs = function validateInputs(inputs) {
var validForm = true;
inputs.each(function(index) {
var input = $(this);
if (!input.val() || (input.type === "radio" && !input.is(':checked'))) {
$("#subnewtide").attr("disabled", "disabled");
validForm = false;
}
});
return validForm;
}
inputs.each(function() {
var input = $(this);
if (input.type === "radio") {
input.change(function() {
if (validateInputs(inputs)) {
$("#subnewtide").removeAttr("disabled");
}
});
} else {
input.keyup(function() {
if (validateInputs(inputs)) {
$("#subnewtide").removeAttr("disabled");
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post" id="myForm">
Title:
<input id="titlenewtide" type="text" name="title" required>
<br>Description:
<textarea name="description" id="description"></textarea>
<br>Tag:
<input id="newtag" type="text" name="newtag" required>
<br>Category:
<input type="radio" name="category" value="19" required>Animation
<button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
</form>
回答by Robin Carlo Catacutan
Use this code below. On each input, it will check all the form fields by using this function validate()
.
在下面使用此代码。在每次输入时,它将使用此函数检查所有表单字段validate()
。
jQuery("input[type='text'], textarea").on("input", function () {
var isValid = validate();
if (isValid) {
jQuery("#subnewtide").removeAttr("disabled");
} else {
jQuery("#subnewtide").attr("disabled", "disabled");
}
});
function validate() {
var isValid = true;
$('input, textarea').each(function() {
if ($(this).val() === '')
isValid = false;
});
return isValid;
}
Update
更新
To make it validate if the form has id="new_tide"
and fix about the radio
button.
使其验证表单是否具有id="new_tide"
并修复radio
按钮。
$("input[type='text'], textarea").on("change input", function() {
validate($(this));
});
$("input:radio[name='category']").on("change", function() {
validate($(this));
});
function validate(self) {
if (self.parents("form:first").attr("id") == "new_tide") {
var isValid = true;
$('input[type="text"], textarea').each(function() {
if ($(this).val() === '')
isValid = false;
});
if (!$("input:radio[name='category']").is(':checked'))
isValid = false;
if (isValid) {
$("#subnewtide").removeAttr("disabled");
} else {
$("#subnewtide").attr("disabled", "disabled");
}
}
}
回答by Johan Karlsson
Here's how you can do it:
您可以这样做:
$(document).ready(function () {
var $inputs = $("#new_tide input:not([type=hidden]), #new_tide textarea");
$inputs.on("input change", function () {
valid = true;
$inputs.each(function () {
valid *= this.type == "radio" ? this.checked : this.value != "";
return valid;
});
$("#subnewtide").prop("disabled", !valid);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form action="#" method="post" id="new_tide">
Title: <input id="titlenewtide" type="text" name="title" required> <br>
Description: <textarea name="description" id="description"></textarea> <br>
Tag: <input id="newtag" type="text" name="newtag" required> <br>
Category: <input type="radio" name="category" value="19" required> Animation
Hidden: <input type="hidden">
<button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
</form>
回答by guest271314
Try utilizing .siblings()
, .map()
to compile values of form
elements , Array.prototype.every()
to return Boolean
representation of input
, textarea
values , set disabled
property of form input[type=submit]
element
尝试利用.siblings()
,.map()
编译form
元素的值,Array.prototype.every()
返回,值的Boolean
表示, 设置元素的属性input
textarea
disabled
form input[type=submit]
$("form *[required]").on("input change", function(e) {
$(this).siblings("[type=submit]").prop("disabled"
, !$(this).siblings(":not([type=submit])").add(this).map(function(_, el) {
return el.type === "radio" ? el.checked : el.value
}).get().every(Boolean)
);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<form action="#" method="post" id="new_tide">
Title: <input id="titlenewtide" type="text" name="title" required> <br>
Description: <textarea name="description" id="description" required></textarea> <br>
Tag: <input id="newtag" type="text" name="newtag" required> <br>
Category: <input type="radio" name="category" value="19" required> Animation
<button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
</form>
回答by adeneo
By far the easiest, would be to rely on the HTML5 validation you're already using.
到目前为止,最简单的方法是依赖您已经在使用的 HTML5 验证。
You'd have to add required
to all form controls if you want to require all of them, and that can easily be done by using jQuery's :input
selector and setting the property, like so
required
如果你想需要所有的表单控件,你必须添加到所有的表单控件中,这可以通过使用 jQuery 的:input
选择器和设置属性轻松完成,就像这样
$(':input:not(#subnewtide)').prop('required', true)
We'll exclude the submit button, as that doesn't have to be required, obviously, not that it would matter in this case.
我们将排除提交按钮,因为这不是必需的,显然,在这种情况下并不重要。
Then we'll listen for the input
event, which covers all sorts of inputs, like typing, pasting etc, and the change
event as well to cover the radio button.
然后我们将侦听input
事件,该事件涵盖各种输入,例如打字、粘贴等,change
以及涵盖单选按钮的事件。
Using form.checkValidity()
tells us if the form is valid, and returns a boolean, so we could use it directly to set the disabled
property of the submit button.
Usingform.checkValidity()
告诉我们表单是否有效,并返回一个布尔值,因此我们可以直接使用它来设置disabled
提交按钮的属性。
All together it looks like this, and that's all you need, a few lines of really simple code
全部看起来像这样,这就是你所需要的,几行非常简单的代码
$(':input:not(#subnewtide)').prop('required', true).on('input change', function() {
$('#subnewtide').prop( 'disabled', !this.form.checkValidity() );
});
If you have to support old browsers that don't have HTML5 validation, you can use the H5F polyfill
如果你必须支持没有 HTML5 验证的旧浏览器,你可以使用H5F polyfill
回答by Paul S.
Thought I might chip in. Assuming as little as possible.
以为我可能会插手。假设尽可能少。
jQuery("input, textarea").on("keyup click", function () { // going vanilla after easy-mode attach
var sub = document.getElementById('subnewtide');
if (require_all(find_form(this))) {
sub.removeAttribute('disabled');
sub.disabled = false;
} else {
sub.setAttribute('disabled', 'disabled');
sub.disabled = true;
}
});
function concat(a, b) { // concating Array-likes produces Array
var slice = [].slice; // not assuming Array.prototype access
return [].concat.call(
slice.call(a, 0),
slice.call(b, 0)
);
}
function find_form(e) { // shim input.form
if (e) do {
if (e.tagName === 'FORM') return e;
} while (e = e.parentNode);
return null;
}
function require_all(form, dontIgnoreHidden) { // looks at textareas & inputs (excluding buttons)
var inp = concat(form.getElementsByTagName('input'), form.getElementsByTagName('textarea')),
rad = {}, // not assuming Object.create
i, j,
has = {}.hasOwnProperty; // not assuming Object.prototype access
for (i = 0; i < inp.length; ++i) {
switch ((inp[i].type || '').toLowerCase()) {
default: // treat unknown like texts
case 'text':
if (!inp[i].value) return false; break;
case 'checkbox':
if (!inp[i].checked) return false; break;
case 'radio':
j = inp[i].getAttribute('name');
if (!rad[j]) rad[j] = inp[i].checked;
break;
case 'hidden':
if (dontIgnoreHidden && !inp[i].value) return false; break;
case 'button':
case 'submit':
break;
}
}
for (j in rad) if (!has || has.call(rad, j)) // not assuming hasOwnProperty
if (!rad[j]) return false;
return true;
}
回答by maytham-???????
My solution is base on standard JavaScript.
我的解决方案基于标准 JavaScript。
HTML form
HTML 表单
<form action="#" method="post" id="new_tide" name="form1">
Title: <input onkeyup="myBtnActivator(1)" id="titlenewtide" name="title" type="text" required> <br>
Description: <textarea onkeyup="myBtnActivator(2)" id="description" name="description"></textarea> <br>
Tag: <input id="newtag" onkeyup="myBtnActivator(3)" name="newtag" type="text" required> <br>
Category: <input name="category" onchange="myBtnActivator(4)" type="radio" value="19" required> Animation
<button id="subnewtide" name="subnewtide" type="submit" value="Submit">Submit</button>
</form>
JavaScript
JavaScript
<script>
document.getElementById("subnewtide").disabled = true;
var input1 = false;
var input2 = false;
var input3 = false;
var input4 = false;
function myBtnActivator(i) {
switch (i) {
case 1:
input1 = true;
if (document.form1.title.value == "")
input1 = false;
break;
case 2:
input2 = true;
if (document.form1.description.value == "")
input2 = false;
break;
case 3:
input3 = true;
if (document.form1.newtag.value == "")
input3 = false;
break;
case 4:
input4 = true;
if (document.form1.subnewtide.value == "")
input4 = false;
break;
}
trigger();
}
function trigger() {
if (input1 == true && input2 == true && input3 == true && input4 == true) {
document.getElementById("subnewtide").disabled = false;
} else {
document.getElementById("subnewtide").disabled = true;
}
}
</script>
回答by PeterKA
Here is a quick way to accomplish that. It involves attaching a change
event listener to :radio
and :checkbox
elements and an input
event listener to other elements. These can both use a common predefined handler
that will count the number of unfilled
element each time each of these events fires on the appropriate element.
这是实现这一目标的快速方法。它涉及将change
事件侦听器附加到:radio
和:checkbox
元素并将input
事件侦听器附加到其他元素。它们都可以使用共同的预定义handler
,unfilled
每次这些事件在适当的元素上触发时,都会计算元素的数量。
function checkForm() {
//define and initialize variables
var unfilled = 0,
form = $(this.form);
//disable submit button if enabled
$(':submit', form).prop('disabled', true);
//count number of unfilled elements
$(':input', form).each(function() {
if( $(this).is(':radio,:checkbox') ) {
$('input[name=' + this.name + ']:checked').length || unfilled++;
} else {
$('[name=' + this.name + ']').val() || unfilled++;
}
});
//enable submit button if no unfilled element is found
unfilled || $(':submit', form).prop('disabled', false);
}
//set up event listeners to fire above handler
$(':text,textarea,select').on('input', checkForm);
$(':radio,:checkbox').on('change', checkForm);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="#" method="post" id="new_tide">
Title: <input id="titlenewtide" type="text" name="title" required> <br>
Description: <textarea name="description" id="description"></textarea> <br>
Tag: <input id="newtag" type="text" name="newtag" required> <br>
Category: <input type="radio" name="category" value="19" required> Animation
<button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
</form>
回答by Ravi Kharinta
var inputs = $("form#myForm input, form#myForm textarea");
var validateInputs = function validateInputs(inputs) {
var validForm = true;
inputs.each(function(index) {
var input = $(this);
if (!input.val() || (input.type === "radio" && !input.is(':checked'))) {
$("#subnewtide").attr("disabled", "disabled");
validForm = false;
}
});
return validForm;
}
inputs.each(function() {
var input = $(this);
if (input.type === "radio") {
input.change(function() {
if (validateInputs(inputs)) {
$("#subnewtide").removeAttr("disabled");
}
});
} else {
input.keyup(function() {
if (validateInputs(inputs)) {
$("#subnewtide").removeAttr("disabled");
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="post" id="myForm">
Title:
<input id="titlenewtide" type="text" name="title" required>
<br>Description:
<textarea name="description" id="description"></textarea>
<br>Tag:
<input id="newtag" type="text" name="newtag" required>
<br>Category:
<input type="radio" name="category" value="19" required>Animation
<button type="submit" value="Submit" name="subnewtide" id="subnewtide" disabled="disabled">Submit</button>
</form>
回答by harilalkm
Why don't you use jquery validate . It's a good plugin .
你为什么不使用 jquery validate 。这是一个很好的插件。
The logic works like, any change in the form it will check the form is valid or not. And also using the errorplacement function it will disable the default error message also.
逻辑的工作原理是,表单中的任何更改都会检查表单是否有效。并且还使用 errorplacement 函数,它还将禁用默认错误消息。
$().ready(function() {
// validate signup form on keyup and submit
$("#contactForm").validate({
rules: {
title: "required",
description: {
required: true
},
newtag: {
required: true
},
category: {
required: true
}
},
errorPlacement: function(error, element) {
return true;
},
submitHandler: function() {
}
});
$('#contactForm').change(function() {
if ($("#contactForm").valid()) {
$("#subnewtide").removeAttr("disabled");
}
});
});