[英]how to adapt this script to include a checkbox check if checked
我對JavaScript完全陌生。 我在我的head
標簽之間使用此腳本,這將迫使用戶在單擊“提交”按鈕之前滾動瀏覽textarea
<script language="JavaScript">
<!--
function textareaAtEnd(textareaObj)
{
return ((textareaObj.scrollTop + textareaObj.offsetHeight) > textareaObj.scrollHeight);
}
function formValidation(formObj)
{
if (textareaAtEnd(formObj.licenseAgreement))
{
return true;
} else {
alert ("Please scroll to the end to move on.")
return false;
}
}
// -->
</script>
我的<form>
看起來像這樣:
<form action="step2.php" method="post" onSubmit="return formValidation(this);">
<textarea name="licenseAgreement" rows="20" cols="90">Very long license agreement text</textarea>
<br />
<input name="agree" type="checkbox" value="yes" /> I have read and agreed the above license agreement
<br />
<input type="submit" value="CONTINUE">
</form>
我如何才能適應此javascript還檢查<input name="agree" type="checkbox" value="yes" />
是否被選中,以及是否不向用戶回顯消息? 我是一個菜鳥,這是我第一次使用javascript。
干得好:
if (document.getElementById('agree').checked == false) {
alert('Check the agree box dummy!');
}
我總是建議使用ID作為客戶端代碼的最佳實踐。
因此,您可以將驗證功能更改為:
function formValidation() {
if (textareaAtEnd(document.getElementById('licenseAgreement')) == false) {
alert ("Please scroll to the end to move on.")
return false;
}
else if (document.getElementById('agree').checked == false) {
alert('Check the agree box dummy!');
return false;
}
else {
return true;
}
}
另外,請確保在您的<input type="checkbox"
和id="licenseAgreement"
的文本區域中添加id="agree"
。
所以它應該看起來像這樣:
<input name="agree" id="agree" type="checkbox" value="yes" />
...
<textarea name="licenseAgreement" id="licenseAgreement" rows="20" cols="90">
然后,您可以在表單標簽中刪除this
參數:
onSubmit="return formValidation();"
做
function formValidation(formObj) {
if(!formObj.agree.checked) {
alert ("Please agree to terms.")
return false;
} else if (textareaAtEnd(formObj.licenseAgreement)) {
return true;
} else {
alert ("Please scroll to the end to move on.")
return false;
}
}
演示: 小提琴
使用checked
屬性:
var checkbox = document.getElementsByName("agree")[0];
if(checkbox.checked)
alert("Check that");
更換
<input name="agree" type="checkbox" value="yes" />
用
<input name="agree" id="agree" type="checkbox" value="yes" />
為復選框添加id=agree
屬性。
if(document.getElementById("agree").checked == false)
{
alert("Checkbox is not checked , please select checkbox");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.