在onlick提交重定向之前验证所需的输入

时间:2020-10-09 21:44:07

标签: html forms input onclick

我正在编写以下HTML代码,该代码需要某些输入值并具有一个提交按钮,单击该按钮可以重定向到其他站点。当前,即使没有在输入框中输入任何值,“提交”按钮也会重定向。我希望只有在所有输入值都填满后,提交按钮才起作用。

<!DOCTYPE html>
<html>
<body>

<h3>Please enter the following information</h3>

<form>
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname" value="" required><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname" value="" required><br>
  <label for="email">Email:</label><br>
  <input type="text" id="email" name="email" value="" required><br>
  <label for="UserID">UserID:</label><br>
  <input type="text" id="UserID" name="UserID" value="" required><br>
  <label for="password">Password:</label><br>
  <input type="password" id="password" name="password" value="" required><br><br>
  <input onclick="window.location.href = 'https://example.site';" type="submit" value="Submit" />
  
</form>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

原因是因为您的提交结构不正确。

您会看到,如果将输入提交替换为按钮,则效果很好:

<!DOCTYPE html>
<html>
<body>

<h3>Please enter the following information</h3>

<form action="https://example.site">
  <label for="fname">First name:</label><br>
  <input type="text" id="fname" name="fname" value="" required><br>
  <label for="lname">Last name:</label><br>
  <input type="text" id="lname" name="lname" value="" required><br>
  <label for="email">Email:</label><br>
  <input type="text" id="email" name="email" value="" required><br>
  <label for="UserID">UserID:</label><br>
  <input type="text" id="UserID" name="UserID" value="" required><br>
  <label for="password">Password:</label><br>
  <input type="password" id="password" name="password" value="" required><br><br>
  <button>Submit</button>
  
</form>
</body>
</html>

您所要做的只是在action中定义的form中添加您要重定向的链接。

这是推荐的方法。

请记住,无论输入字段中是否有required属性,您都应始终执行服务器端检查,因为该属性很容易删除。