[英]Form validation with JS not working
HTML
<form name="suggestion" method="post" action="suggestion.php"
class="elegant-aero" onSubmit="return validate()" >
<label>
<span>Message :</span>
<textarea id="Message" name="message" placeholder="Your Message to Us"></textarea>
</label>
<input type="submit" class="buttonc" value="SEND" onclick="validate()">
</form>
JavaScript的
function validate() {
var message = document.suggestion.message.value;
if (message == "") {
alert("Message box should not be leaved empty");
return false;
} else {
return true;
}
}
難道我做錯了什么? 我的驗證功能不起作用。 請給我一些建議。
我認為主要的錯誤在於,按照我的理解, document.suggestion.message.value
不是有效的選擇器。 嘗試使用getElementById
來選擇該表單。
要通過名稱訪問表單,您必須執行以下操作:
var message = document.forms["suggestion"].elements["message"].value;
但是更好的方法是使用ID 。
但
最簡單的方法是在<textarea>
設置所需的屬性
<textarea required>
代碼不錯,但是您必須在文檔中正確放置腳本
看這里http://jsfiddle.net/wLrg26s0/4/在jsbin的左側no wrap - in <body>
選擇no wrap - in <body>
它的意思是代碼看起來像
<body>
<!-- page -->
<script>
//js here
</script>
<body>
函數以這種方式聲明轉到window
名稱空間。 它的全局名稱空間,並存在onSubmit
搜索validate
功能。
如果在jsbin onLoad
左側選擇,則代碼看起來像(並且不要忘記單擊運行)
<script>
$( document ).ready(function() {
//js here
});
</script>
而且腳本不起作用,因為函數是在其他地方聲明的。 要解決此問題,您必須以這種方式聲明功能
window.validate = function(){ /*code */}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.