2012-11-30 40 views
0

我做的PHP是文字框爲空值時,它會打開一個alertbox(我使用javascript在這裏)PHP的JavaScript alertbox必須點擊2次拿給

這是我的代碼

<?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次

請幫我解決這個問題

回答

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> 

編輯:

我搬到了頭內的腳本標籤標籤。我不確定是否有任何影響讓腳本在外面,但只是爲了確保我已將其移出。

2日編輯:(OCD被踢)

我已經添加body標籤,不知道你是否複製並粘貼此代碼,但它看上去怪我:)

相關問題