2013-03-03 121 views
-1

同時提交我的表單不會驗證。我正在使用提交表單提交,我必須重定向我的頁面。通過使用onclick事件應該驗證..javascript不工作在php

<td id="main"> 
    <h2>Add Info </h2> 
    <form action="create_info.php" name="f1" method="post"> 
    <p>Info Title: 
     <input type="text" name="menu" value="" id="menu" /> 
    </p> 
    <p>Position: 
     <select name="position"> 
     <?php 
     $info_set = get_all_info(); 
     $info_count = mysql_num_rows($info_set); 
     for($count=1; $count <=$info_count+1; $count++){ 
     echo " <option value=\"{$count}\">{$count}</option>"; 
     } 
     ?> 
     </select> 
    </p> 
    <p>Visible: 
     <input type="radio" name="visible" value="0" />NO 
     <input type="radio" name="visible" value="1" />YES 
    </p> 
    <input type="submit" value="Add" onclick="validateForm()"/> 
    </form> 
    <br> 
    <a href="content.php">Cancel</a> 
</td> 
</tr> 
</table> 
</div> 
<script language="text/java script"> 
    function validateForm() 
    { 
    if(f1.menu.value== "") 
    { 
     alert("name must be filled out"); 
     return false; 
    } 
    } 
</script> 
+0

的''的元素script'的language'屬性早就已經過時了。改用'type =「text/javascript」'。你在哪裏定義'f1'? – 2013-03-03 17:15:41

+2

@MarcelKorpel因爲它是所有現代瀏覽器中的默認腳本,所以不需要這麼做。 – 2013-03-03 17:17:49

+0

@ jimjimmy1995:正確,但如果OP使用HTML 4.01或XHTML(爲了驗證),應該定義它。 – 2013-03-03 17:21:30

回答

0

它沒有驗證,因爲你沒有阻止提交事件。你應該把你的驗證放在onsubmit事件中,當你點擊提交按鈕時它會被觸發。在的jsfiddle

工作代碼:http://jsfiddle.net/FHZKr/

<form action="create_info.php" name="f1" method="post" onsubmit="return validateForm();"> 
    <p>Info Title: 
    <input type="text" name="menu" value="" id="menu" /> 
    </p> 
    <p>Position: 
     <select name="position"> 
     <?php 
     $info_set = get_all_info(); 
     $info_count = mysql_num_rows($info_set); 
     for($count=1; $count <=$info_count+1; $count++){ 
     echo " <option value=\"{$count}\">{$count}</option>"; 
     } 
     ?> 
     </select> 
    </p> 
    <p>Visible: 
    <input type="radio" name="visible" value="0" />NO 
    <input type="radio" name="visible" value="1" />YES 
    </p> 
    <input type="submit" value="Add" /> 
</form> 

的JavaScript

<script type="text/javascript"> 

function validateForm() 
{ 
    if(f1.menu.value== "") 
    { 
     alert("name must be filled out"); 
     return false; 
    } 
    return true; 
} 
</script> 
+0

對不起,像靜態頁面derek它ack ..什麼都沒做... – user2032629 2013-03-03 17:30:46

+0

糟糕...在以前的版本中有錯字。嘗試一下。將腳本標記從'language =「text/java script」'更新爲'type =「text/javascript」' – Derek 2013-03-03 17:43:11