检查输入字段是否为空

时间:2014-02-09 14:20:48

标签: javascript php jquery html validation

我在我的网站的其他地方使用过以下代码,但它确实有效。对于我的生活,我无法理解为什么它在这里不起作用。问题:不断抛出警报信息。

我的HTML:

<form action="processForms.php" method="post" id="joinCommitteeForm" class="headForm shadow">
                <div class="outerBlue" style="background:white">
                    <button type="button" id="cancelForm" class="button" title="Cancel">X</button>
                <br><br>
                <h3>Get involved&mdash;join a committee!</h3>

                <?php if(empty($name)||empty($email)||empty($workPhone)){
                echo "<p class='red'>All fields must be filled out...</p><br><br>";
                }?>
                <label for="name" style="width:40px">Name</label><input type="text" name="name" id="name"/><br>
                <label for="email" style="width:40px" class="clear">Email</label><input type="text" name="email" id="email"/><br>
                <label for="phone" style="width:40px;margin-bottom:20px" class="clear">Phone</label><input type="text" name="dayPhone" id="phone"/>
                <hr>
                <p class="clear">Please select a committee from the list below</p><br><br>
                <select name="comName" id="comName" style="width:215px;margin-left:50px;float:left">
                <option value="">Select one...</option>
                <?php
                $sql = mysql_query("SELECT committeeName FROM committeeName ORDER BY committeeName");
                while ($row = mysql_fetch_assoc($sql)){
                    echo "<option value = '".$row['committeeName']."'>".$row['committeeName']."</option>";
                }
                echo "</select>";?>
                <input type="submit" name="submitCommitteeInterest" class="button orange-button clear" value="Submit" style="margin-top:40px"/>
                <div class="clear"></div>
                <p class="small white" style="line-height:1em;margin-top:20px">NSGP never sells or gives away your personal information</p>
            </div>
            </form>

我的JS:

$("#joinCommitteeForm").submit(function() {
        if ($.trim($("#email").val()) === "" || $.trim($("#name").val()) === "") {
            alert('All fields are required');
            return false;
        }
    });

1 个答案:

答案 0 :(得分:0)

我怀疑问题出在这里,就是您正在测试$name$email是否为空,但由于您从未定义它们,因此PHP empty() docs始终为空:“如果变量不存在或者其值等于FALSE”,则该变量被视为空。

要解决此问题,您需要将PHP if语句更改为:

<?php if(empty($_POST['name'])||empty($_POST['email'])||empty($_POST['dayPhone'])){
  echo "<p class='red'>All fields must be filled out...</p><br><br>";
}?>

此外,您的POST参数$workPhone似乎不存在于您的表单中。我已将其更改为dayPhone

变量$_POST将包含来自提交表单的POST请求中的所有参数。