我大约 5-10 分钟前才开始学习 JS,有人告诉我尝试创建一个基本的验证功能,但它似乎并没有按预期工作。它检查字段是否为空,该部分是否有效。但是检查它是否包含某些内容并继续运行代码却没有。
我的表单:
echo '<form action="index.php?action=getHashedText" method="post" name="formHash">
<br/><textarea name="text" rows="4" cols="50" placeholder="Add your text/pharse/word which you want hashing here." autofocus></textarea><br/>
<button type="button" name="button" onclick="return validate();">Hash</button>';
函数验证():
<script>
function validate() {
with (window.document.formHash) {
if (formHash.text.value === "") {
alert('Field is empty!');
return false;
} else {
return true;
}
}
}
</script>
最佳答案
问题是您使用的按钮无论如何都不会提交表单(无论您的 js 是什么),请更改此 dom:
<button type="button" name="button" onclick="return validate();">Hash</button>
对此:Fiddle
<input type="submit" name="button" value="Hash" onclick="return validate();" />
或者您可以只添加 type="submit"
在你的 <button>
(HT @RocketHazmat):Fiddle
<button type="submit" name="button" onclick="return validate();">Hash</button>
或者您可以只删除 type
在你的 <button>
所有一起作为默认 type
是submit
(HT @FabrícioMatté):Fiddle
<button name="button" onclick="return validate();">Hash</button>
此外,稍微偏离主题,但我会养成避免将 javascript onclicks 直接放在元素上的习惯。您可以改为创建监听器:addEventListener
关于php - 为什么我的返回不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18132159/