我遇到了一些与此非常相似的问题 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/