-1

在提交我的表单时,它不会验证。我使用提交进行表单提交,我必须重定向我的页面。通过使用 onclick 事件,它应该被验证..

<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>
4

1 回答 1

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>
于 2013-03-03T17:19:25.837 回答