繁体   English   中英

检查输入字段是否为空

[英]Check if input field empty

我在网站的其他地方使用了下面的代码,它可以正常工作。 对于我的一生,我不明白为什么它在这里不起作用。 问题:不断抛出警报消息。

我的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;
        }
    });

我怀疑这里的问题是,您正在测试$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请求中的所有参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM