2013-03-15 75 views
0

我是JavaScript的總noob。我用我的head標籤之間的腳本,這將迫使用戶點擊提交按鈕如何適應這個腳本包括複選框檢查,如果選中

<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> 

之前通過textarea滾動我<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" />是否被選中並且是否不向用戶回送消息?我是一個總noob,這是我第一次使用JavaScript。

回答

0

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; 
    } 

} 

演示:Fiddle

+0

非常感謝你,這個工作 – 2013-03-15 08:10:15

0

在這裏你去:

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; 
    } 
} 

此外,一定要一個id="agree"添加到您的<input type="checkbox"id="licenseAgreement"您的textarea ...

因此,它應該是這樣的:

<input name="agree" id="agree" type="checkbox" value="yes" /> 

... 

<textarea name="licenseAgreement" id="licenseAgreement" rows="20" cols="90"> 

而你的表格標籤,你可以刪除this參數:

onSubmit="return formValidation();" 
0

使用checked屬性:

var checkbox = document.getElementsByName("agree")[0]; 

if(checkbox.checked) 
    alert("Check that"); 
+0

返回元素的數組... – 2013-03-15 08:07:05

+0

'getElementsByName'返回一個集合。 – gdoron 2013-03-15 08:07:31

+0

錯字,對不起! :) – Bigood 2013-03-15 08:07:47

0

更換

<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"); 
} 
相關問題