Javascript 禁用/启用提交按钮,直到填写完所有表格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13931688/
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
Disable/Enable Submit Button until all forms have been filled
提问by user1912654
I want my form submit button to be disabled/enabled depending on if the form is completely filled.
我希望我的表单提交按钮被禁用/启用,具体取决于表单是否完全填写。
When the inputs are filled, the disabled button changes to enabled. That works great. But I would like it to disable the button when an input gets emtied.
当输入被填满时,禁用按钮变为启用。这很好用。但我希望它在输入被清除时禁用按钮。
This is my script:
这是我的脚本:
<script type="text/javascript" language="javascript">
function checkform()
{
var f = document.forms["theform"].elements;
var cansubmit = true;
for (var i = 0; i < f.length; i++) {
if (f[i].value.length == 0) cansubmit = false;
}
if (cansubmit) {
document.getElementById('submitbutton').disabled = false;
}
}
</script>
<form name="theform">
<input type="text" onKeyup="checkform()" />
<input type="text" onKeyup="checkform()" />
<input id="submitbutton" type="submit" disabled="disabled" value="Submit" />
</form>
回答by Bergi
Just use
只需使用
document.getElementById('submitbutton').disabled = !cansubmit;
instead of the the if-clause that works only one-way.
而不是只有一种方式的 if 子句。
Also, for the users who have JS disabled, I'd suggest to set the initial disabledby JS only. To do so, just move the script behind the <form>and call checkform();once.
另外,对于禁用 JS 的用户,我建议disabled仅通过 JS设置初始值。为此,只需将脚本移到 后面<form>并调用checkform();一次。
回答by Mario Sannum
Just add an elsethen:
只需添加一个elsethen:
function checkform()
{
var f = document.forms["theform"].elements;
var cansubmit = true;
for (var i = 0; i < f.length; i++) {
if (f[i].value.length == 0) cansubmit = false;
}
if (cansubmit) {
document.getElementById('submitbutton').disabled = false;
}
else {
document.getElementById('submitbutton').disabled = 'disabled';
}
}
回答by dinafication
Put it inside a table and then do on her:
把它放在桌子上,然后在她身上做:
var tabPom = document.getElementById("tabPomId");
$(tabPom ).prop('disabled', true/false);
回答by Vignesh A
Here is the code
这是代码
<html>
<body>
<input type="text" name="name" id="name" required="required" aria-required="true" pattern="[a-z]{1,5}" onchange="func()">
<script>
function func()
{
var namdata=document.form1.name.value;
if(namdata.match("[a-z]{1,5}"))
{
document.getElementById("but1").disabled=false;
}
}
</script>
</body>
</html>
Using Javascript
使用 JavaScript
回答by M. Lak
You can enable and disable the submit button based on the javascript validation below is the validation code. Working Example Here
您可以根据下面的验证代码启用和禁用提交按钮。这里的工作示例
<script>
function validate() {
var valid = true;
valid = checkEmpty($("#name"));
valid = valid && checkEmail($("#email"));
$("#san-button").attr("disabled",true);
if(valid) {
$("#san-button").attr("disabled",false);
}
}
function checkEmpty(obj) {
var name = $(obj).attr("name");
$("."+name+"-validation").html("");
$(obj).css("border","");
if($(obj).val() == "") {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Required");
return false;
}
return true;
}
function checkEmail(obj) {
var result = true;
var name = $(obj).attr("name");
$("."+name+"-validation").html("");
$(obj).css("border","");
result = checkEmpty(obj);
if(!result) {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Required");
return false;
}
var email_regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,3})+$/;
result = email_regex.test($(obj).val());
if(!result) {
$(obj).css("border","#FF0000 1px solid");
$("."+name+"-validation").html("Invalid");
return false;
}
return result;
}
</script>
回答by Edwinfad
I think this will be much simpler for beginners in JavaScript
我认为这对于 JavaScript 初学者来说会简单得多
//The function checks if the password and confirm password match
// Then disables the submit button for mismatch but enables if they match
function checkPass()
{
//Store the password field objects into variables ...
var pass1 = document.getElementById("register-password");
var pass2 = document.getElementById("confirm-password");
//Store the Confimation Message Object ...
var message = document.getElementById('confirmMessage');
//Set the colors we will be using ...
var goodColor = "#66cc66";
var badColor = "#ff6666";
//Compare the values in the password field
//and the confirmation field
if(pass1.value == pass2.value){
//The passwords match.
//Set the color to the good color and inform
//the user that they have entered the correct password
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Passwords Match!"
//Enables the submit button when there's no mismatch
var tabPom = document.getElementById("btnSignUp");
$(tabPom ).prop('disabled', false);
}else{
//The passwords do not match.
//Set the color to the bad color and
//notify the user.
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
message.innerHTML = "Passwords Do Not Match!"
//Disables the submit button when there's mismatch
var tabPom = document.getElementById("btnSignUp");
$(tabPom ).prop('disabled', true);
}
}
回答by NIKHIL CHANDRA ROY
<form name="theform">
<input type="text" />
<input type="text" />`enter code here`
<input id="submitbutton" type="submit"disabled="disabled" value="Submit"/>
</form>
<script type="text/javascript" language="javascript">
let txt = document.querySelectorAll('[type="text"]');
for (let i = 0; i < txt.length; i++) {
txt[i].oninput = () => {
if (!(txt[0].value == '') && !(txt[1].value == '')) {
submitbutton.removeAttribute('disabled')
}
}
}
</script>
回答by NIKHIL CHANDRA ROY
Here is my way of validating a form with a disabled button. Check out the snippet below:
这是我验证带有禁用按钮的表单的方法。看看下面的片段:
var inp = document.getElementsByTagName("input");
var btn = document.getElementById("btn");
// Disable the button dynamically using javascript
btn.disabled = "disabled";
function checkForm() {
for (var i = 0; i < inp.length; i++) {
if (inp[i].checkValidity() == false) {
btn.disabled = "disabled";
} else {
btn.disabled = false;
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>JavaScript</title>
</head>
<body>
<h1>Javascript form validation</h1>
<p>Javascript constraint form validation example:</p>
<form onkeyup="checkForm()" autocomplete="off" novalidate>
<input type="text" name="fname" placeholder="First Name" required><br><br>
<input type="text" name="lname" placeholder="Last Name" required><br><br>
<button type="submit" id="btn">Submit</button>
</form>
</body>
</html>
Example explained:
示例说明:
- We create a variable to store all the input elements.
var inp = document.getElementsByTagName("input"); - We create another variable to store the button element
var btn = document.getElementById("btn"); - We loop over the collection of input elements
for (var i = 0; i < inp.length; i++) { // Code } - Finally, We use the
checkValidity()method to check if the input elements (with arequiredattribute) are valid or not (Code is inserted inside the for loop). If it is invalid, then the button will remain disabled, else the attribute is removed.for (var i = 0; i < inp.length; i++) { if (inp[i].checkValidity() == false) { btn.disabled = "disabled"; } else { btn.disabled = false; } }
- 我们创建一个变量来存储所有输入元素。
var inp = document.getElementsByTagName("input"); - 我们创建另一个变量来存储按钮元素
var btn = document.getElementById("btn"); - 我们遍历输入元素的集合
for (var i = 0; i < inp.length; i++) { // Code } - 最后,我们使用
checkValidity()方法来检查输入元素(带有required属性)是否有效(代码被插入到 for 循环中)。如果无效,则按钮将保持禁用状态,否则该属性将被删除。for (var i = 0; i < inp.length; i++) { if (inp[i].checkValidity() == false) { btn.disabled = "disabled"; } else { btn.disabled = false; } }
回答by jecz
I just posted this on Disable Submit button until Input fields filled in. Works for me.
我刚刚在禁用提交按钮上发布了这个,直到输入字段填写。为我工作。
Use the form onsubmit. Nice and clean. You don't have to worry about the change and keypress events firing. Don't have to worry about keyup and focus issues.
使用提交时的表单。漂亮干净。您不必担心触发更改和按键事件。不必担心按键和焦点问题。
http://www.w3schools.com/jsref/event_form_onsubmit.asp
http://www.w3schools.com/jsref/event_form_onsubmit.asp
<form action="formpost.php" method="POST" onsubmit="return validateCreditCardForm()">
...
</form>
function validateCreditCardForm(){
var result = false;
if (($('#billing-cc-exp').val().length > 0) &&
($('#billing-cvv').val().length > 0) &&
($('#billing-cc-number').val().length > 0)) {
result = true;
}
return result;
}

