6

我知道 javascript 在初级阶段,但我有一个问题。

我在一个表单中有7 个输入元素,我希望它们都被填充。我想出了这个主意,但它看起来很恶心

有人可以帮我检查是否所有表单元素都已填写吗?

function validateForm()
{
var x=document.forms["register"]["name"].value;
var y=document.forms["register"]["phone"].value;
var z=document.forms["register"]["compname"].value;
var q=document.forms["register"]["mail"].value;
var w=document.forms["register"]["compphone"].value;
var e=document.forms["register"]["adres"].value;
var r=document.forms["register"]["zip"].value;
if (x==null || x=="" || y==null || y=="" || z==null 
|| z=="" || q==null || q=="" ||  w==null || w=="" || e==null || e=="" 
|| r==null || r=="")
{
alert("Please fill all the inputs");
return false;
}
}
</script>
4

4 回答 4

13

这是简单而肮脏的方式。

更好的方法是更新需要字段的验证消息。

function validateForm()
{
  var fields = ["name, phone", "compname", "mail", "compphone", "adres", "zip"]

  var i, l = fields.length;
  var fieldname;
  for (i = 0; i < l; i++) {
    fieldname = fields[i];
    if (document.forms["register"][fieldname].value === "") {
      alert(fieldname + " can not be empty");
      return false;
    }
  }
  return true;
}
于 2013-07-29T20:31:36.787 回答
6

使用一些简单的 vanilla JS,您可以以更简化的方式处理此问题:

JavaScript

function validateForm(){
    var form = document.getElementById("register"), inputs = form.getElementsByTagName("input"), input = null, flag = true;
    for(var i = 0, len = inputs.length; i < len; i++) {
        input = inputs[i];
        if(!input.value) {
            flag = false;
            input.focus();
            alert("Please fill all the inputs");
            break;
        }
    }
    return(flag);
}

然后确保你return的表单中的函数,或者内联(不好的做法):

<form name="register" id="register" method="post" action="path/to/handler.php" onsubmit="return validateForm();">

或者以更不显眼的方式:

window.onload = function(){
    var form = document.getElementById("register");
    form.onsubmit = function(){
        var inputs = form.getElementsByTagName("input"), input = null, flag = true;
        for(var i = 0, len = inputs.length; i < len; i++) {
            input = inputs[i];
            if(!input.value) {
                flag = false;
                input.focus();
                alert("Please fill all the inputs");
                break;
            }
        }
        return(flag);
    };
};
于 2013-07-29T20:40:13.890 回答
0
<html>

<head>
  <title> Event Program</title>
  <script>
  function validateForm() {
    var fields = ["name, phone", "compname", "mail", "compphone", "adres", "zip"]
    var i, l = fields.length;
    var fieldname;
    for(i = 0; i < l; i++) {
      fieldname = fields[i];
      if(document.forms["register"][fieldname].value === "") {
        alert(fieldname + " can not be empty");
        return false;
      }
    }
    return true;
  }

  var _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"];
  var fields = {
    "eventName": "Event Name",
    "eventDate": "Event Date",
    "eventPlace": "Event Place"
  }

  function Validate(oForm) {
    var arrInputs = oForm.getElementsByTagName("input");
    for(var i = 0; i < arrInputs.length; i++) {
      var oInput = arrInputs[i];
      if(oInput.type == "text" && oInput.value == "") {
        alert(fields[oInput.name] + " cannot be empty");
        return false;
      }
      if(oInput.type == "file") {
        var sFileName = oInput.value;
        if(sFileName.length > 0) {
          var blnValid = false;
          for(var j = 0; j < _validFileExtensions.length; j++) {
            var sCurExtension = _validFileExtensions[j];
            alert(sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase())
            if(sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
              blnValid = true;
              break;
            }
          }

          if(!blnValid) {
            alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
            return false;
          }
        }
      }
    }

    return true;
  }

  </script>

</head>

<body>
  <div align="center">
    <h3>Event Management</h3>
    <form onsubmit="return Validate(this);" id='eventForm' name='eventForm' method='POST' enctype='multipart/form-data' action='saveEvent.php'>
      <table>
        <tr>
          <td>Event Name</td>
          <td>
            <input type="text" name="eventName">
          </td>
        </tr>
        <tr>
          <td>Event Date</td>
          <td>
            <input type="text" name="eventDate" id='datepicker'>
          </td>
        </tr>
        <tr>
          <td>Event place</td>
          <td>
            <input type="text" name="eventPlace">
          </td>
        </tr>
        <tr>
          <td>Upload Image</td>
          <td>
            <input type="file" name="my file" />
            <br />
          </td>
        </tr>
        <tr>
          <td>About Events</td>
          <td>
            <textarea></textarea>
          </td>
        </tr>
        <tr>
          <td colspan=2 align=center>
            <input type="submit" value="Submit" />
            <input type="button" name="clear" value="Clear" />
          </td>
        </tr>
      </table>
    </form>
  </div>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
  <script>
  $(function () {
    $("#datepicker").datepicker({
      dateFormat: "dd/mm/yy",
      changeMonth: true,
      changeYear: true
    }).datepicker("setDate", new Date());
  });

  </script>
</body>

</html>
于 2015-06-28T10:09:04.020 回答
-2

你可以这样做:

//Declare variables
var 1, 2, 3, 4, 5, 6, 7;
1 = document.getElementById("Field Id");
2 = document.getElementById("Field Id");
3 = document.getElementById("Field Id");
4 = document.getElementById("Field Id");     //Define variable values
5 = document.getElementById("Field Id");
6 = document.getElementById("Field Id");
7 = document.getElementById("Field Id");

//Check if any of the fields are empty
If (1 == "" || 2 == "" || 3 == "" || 4 == "" || 5 == "" || 6 == "" || 7 == "") {
  alert("One or more fields are empty!");
  //Other code
}

我将它用于我自己的表单,它工作正常,同时不占用太多空间或看起来太“丑陋”。它适用于所有字段元素并检查输入的值。

于 2013-07-30T18:21:35.850 回答