javascript - 消息提示 onsubmit return validate 但表单仍然提交

标签 javascript php jquery validation

我遇到了一些与此非常相似的问题 onsubmit return false does not work, form still submits? 我按照解决方案做了,但是如果我把它改成onclick,就不行了,连消息提示都没有。

我正在使用的脚本。

<script>
function validate()
{
  var validate = false;
  if(document.getElementById("nameId").value == "")
  {  
    alert("NAME IS REQUIRED");
    validate   = false
  }

return true ;
}

</script>

我的代码附在下面。

<table class="<?php echo $table_style_3;?>" style='width: auto;'>
<form action="fhd_add_type.php" method="post" class="form-horizontal"   onsubmit="return validate()"> //This is the part where i've changed to onclick
<input type='hidden' name='nacl' value='<?php echo $nacl;?>'>
<input type='hidden' name='type' value='<?php echo $type;?>'>
<?php
if ($type <> 0) { ?>
    <tr><td>Name: </td><td><input type='text' name='type_name' id = "nameId"></td></tr> //This is the field where need to be validate
    <tr><td colspan='2'><input type='submit' value='add' class='btn btn-primary'></td></tr>
    </table>
<?php  }
if ($type == 0) { ?>
    <tr><td>Name</td><td><input type='text' name='type_name' id = "nameId"></td></tr> //This is the field where need to be validate
    <tr><td>Email</td><td><input type='text' name='type_email'></td></tr>
    <tr><td>Location</td><td><input type='text' name='type_location'></td></tr>
    <tr><td>Phone</td><td><input type='text' name='type_phone'></td></tr>
    <tr><td colspan='2'><input type='submit' value='add' class='btn btn-primary'></td></tr>
    </table>
<?php }?>
</form>
</table>

最佳答案

我认为这是因为你总是返回true。在你的 JS 中,试试这个:

<script>
function validate()
{
  var validate = true;
  if(document.getElementById("nameId").value == "") {  
       alert("NAME IS REQUIRED");
       validate = false;
    }

    return validate;
}
</script>

关于javascript - 消息提示 onsubmit return validate 但表单仍然提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44403405/

相关文章:

javascript - Typescript - 在模块内找不到构造函数方法

php - 妥善处理 "POST Content-Length of bytes exceeds the limit of"警告

jquery - 如何使用 jQuery 跟踪用户何时在下拉列表选项上按下 Enter?

java - Java 中的 curl HTTPS 实现

javascript - 重复函数,同时递增 [i]

javascript - 单击链接时如何禁用淡入/淡出 div

javascript - 是否有编译为 javascript 的 lisp?

javascript - 使用 Hapijs 处理和发送大量数据

javascript - 在 jQuery 滚动条上淡入淡出 div

php - 我可以将整个代码文件夹复制粘贴到 SVN 存储库中吗