如何在html标签“必需”和javascript“onClick”之间排序顺序

问题描述 投票:1回答:3

我有一个简单的表单来将项目添加到使用PHP构建的数据库中。我使用html属性需要像这样:

<input type="text" name="iditem" required/>

防止将空白值发送到数据库中的提交按钮。

我也在提交按钮上有javascript“onClick”,如下所示:

<input type="submit" onClick="return confirm('Add this item?')" />

我想问的是......如何在提交按钮之前首先执行必需的属性?

多谢你们...

javascript php onclick
3个回答
0
投票

你可以在<form>中使用“onsubmit”参数,并避免提交按钮上的“onclick”:

<form action="test2.php" onsubmit="return confirm('Add this item?')" >
  <input type="text" required />
  <input type="submit" />
</form>

0
投票

<!DOCTYPE html>
<html>
<body>

<form action="">
  Username: <input type="text" name="usrname" required>
  <input type="submit">
</form>

</body>
</html>

0
投票

这里一个简单的方法是使用普通的JavaScript来完成所有繁重的工作。我们来看看吧。

首先,我们设置HTML表单

<!DOCTYPE html>
<html>
<body>

<form action="/" method="post" onsubmit="return validateForm();">
  Username: <input id="username" type="text" name="username">
  <input type="submit">
</form>

</body>
</html>

现在,请注意提及formmethodactiononsubmit指令。让我们逐个讨论所有这些。

我相信你完全知道methodaction做了什么,但是对于onsubmit部分,它与一个名为validateForm()的JavaScript函数相关联,定义如下:

function validateForm() {
  var username = document.getElementById( 'username' ).value;
  if( !username ) {
    return false;
  } 

  return true;
}

此函数获取表单中username元素的值,如果它为空则返回false,否则返回true。它的作用是它告诉事件触发器继续使用action动词将表单提交给method,如果结果值是true;如果它是false,它只是停止执行。就像我们使用return关键字来打破当前控件一样。

所以,在某种程度上,它是在你的onClick处理程序之前触发的。以一种非常微妙的方式,如果验证失败,它将不会让表单被发布。

现在,当然,您可以通过添加confirm对话来编辑它以满足您的需要,因为如果按下trueOK它将返回YES,否则返回false。但是这应该给你一个很好的例子,你可以用onsubmit attribute,特别是event attributes

我希望这回答了你的问题!你可以找到一个小提琴here

© www.soinside.com 2019 - 2024. All rights reserved.