Javascript:如何在所有字段都经过验证之前禁用提交按钮?

时间:2016-08-07 01:37:03

标签: javascript function button submit disabled-control

我有几个验证函数可以正常工作,我想在简单的javascript(没有jQuery等)中为整个表单编写一个额外的验证,禁用/启用Submit按钮取决于是否其他验证函数返回true或false。我该怎么做?

例如,对于我的主HTML,我有:

 <form id="form" method="POST">
      <label class="form">Field 1</label><input type="text" name="input1" onkeyup="validateInput1(); return false">
      <label class="form">Field 2</label><input type="text" name="input2" onkeyup="validateInput2(); return false">
      ...
      <button id="submit" type="submit" value="submit">Submit</button>
 </form>

我的剧本有:

 function validateInput1(){
 ...
 }

 function validateInput2(){
 ...
 }

现在我想用类似的东西编写一个函数:

function validateForm(){

    var submitButton = document.getElementById('submit');
    submitButton.disabled = true;

    /*If all other validation functions like validateInput1() returns true then submitButton.disabled = false*/
}

我该怎么做?

1 个答案:

答案 0 :(得分:2)

禁用时关闭按钮。挂钩每个表单输入的onchange事件,然后检查validateForm()函数以查看所有表单是否有效。之后,如果它们全部有效,请将提交按钮设置为启用,否则将其设置为禁用。

&#13;
&#13;
var inputs = document.querySelectorAll('#form input');

var validateInput1 = function()
{
  return document.getElementById('input1').value != '';
}

var validateInput2 = function()
{
  return document.getElementById('input2').value != '';
}
    
var validateForm = function() {

  if ( !validateInput1() ) {
    return false;
  }

  if ( !validateInput2() ) {
    return false;
  }

  return true;
}

for ( var i = 0, len = inputs.length; i < len; i++ )
{
  var checkValid = function() {
    document.getElementById('submit').disabled = !validateForm();
    
    //Is the same as:
    /*if ( !validateForm() )
    {
      document.getElementById('submitButton').disabled = true;
    }
    else
    {
      document.getElementById('submitButton').disabled = false;
    }*/
  }
  
  inputs[i].addEventListener('change', checkValid);
  inputs[i].addEventListener('keyup', checkValid);
}
&#13;
<form id="form" method="POST" onsubmit="alert('Submitted!'); return false">
    <label class="form">Field 1</label><input type="text" name="input1" id="input1">
    <label class="form">Field 2</label><input type="text" name="input2" id="input2">
    <button id="submit" type="submit" value="submit" disabled="disabled">Submit</button>
</form>
&#13;
&#13;
&#13;