php javascript警告框必须在显示之前单击2次

时间:2012-11-30 09:39:41

标签: php javascript html

我正在做的文本框是一个空值,它会打开一个警告框(我在这里使用javascript)

这是我的代码

    <?php 
    include('config.php');

        if(isset($_POST['submit'])){
        $username=$_POST['username'];

    ?>

    <script>
        function validate(){
        if(document.forms[0].username.value==""){
          window.alert("You must enter both values");
          return false;
        }
        }
    </script>

    <?php
    }
    ?>



<html>
<div><p>Member Profile</p>
    <form action="testing.php" method="POST" onsubmit="return validate();">
    Username<br>
    <input class="user" type="text" name="username" id="username" /><br>


<input type="submit" name="submit" value="register" />
</form>
</div>

</html>

问题是我必须在提醒节目之前点击2次

请帮我解决这个问题

1 个答案:

答案 0 :(得分:3)

这是因为脚本在php if(isset){}块内,单击提交表单,生成脚本然后第二次工作..请尝试此设置:

<?php
    include ('config.php');

    if (isset($_POST['submit']))
    {
        $username = $_POST['username'];
    }
?>
<html>
    <head>
        <script>
            function validate () {
                if (document.forms[0].username.value == "") {
                    window.alert("You must enter both values");
                    return false;
                }
            }
        </script>
    </head>
    <body>
        <div>
            <p>
                Member Profile
            </p>
            <form action="testing.php" method="POST" onsubmit="return validate();">
                Username
                <br>
                <input class="user" type="text" name="username" id="username" />
                <br>

                <input type="submit" name="submit" value="register" />
            </form>
        </div>
    </body>
</html>

编辑:

我已经在head标签内移动了脚本标签。我不确定是否有任何影响将脚本放在外面但只是为了确保我已移动它。

第二编辑:(强迫症正在开始)

我添加了body标签,不确定您是否复制并粘贴了此代码,但对我来说看起来很奇怪:))