我对单选按钮和复选框有问题。
请参阅下面的片段。思路如下:当用户按下"我想参与"按钮时,代码应检查用户是否选中了该复选框,如果没有,则发出警报。
警报在需要时会引发,但是当我关闭它时,复选框会被标记,即使它不是以前。为什么会这样?
多谢!
<html>
<body>
<div id="consent"></div>
</body>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript">
function consent() {
var HTMLtext = "<label> <input type='checkbox' name='cons' value='agree' id='consAgree' /> I am age 18 or older and understand the information above. <label><br>";
HTMLtext += "<br><span id='submit_cons'><button type='button' onClick='javascript:evaluateConsent()'>I want to participate </button></span>";
document.getElementById('consent').innerHTML = HTMLtext;
}
function evaluateConsent() {
var isOK = 1;
if(document.getElementById("consAgree").checked == false) {
isOK = 0;
}
if(isOK == 0) {
alert('Please make sure you have confirmed all three conditions.nIf you do not want ot participate, return the HIT');
}
else {
var HTMLtext = "Thank you! Now take a look at the example!";
document.getElementById('submit_cons').innerHTML = HTMLtext + "<hr>";
}
}
/*--MAIN--*/
function main(){
consent();
}
$(document).ready(function() {
//Ensure that form is not submitted upon pressing Enter key
$(window).keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
});
//call function to run experiment
main();
});
</script>
</head>
</html>
您正在关闭label
标签,如下所示:<label>
,这是对此</label>
的错误更改
function consent() {
var HTMLtext = "<label> <input type='checkbox' name='cons' value='agree' id='consAgree' /> I am age 18 or older and understand the information above. </label><br>";
HTMLtext += "<br><span id='submit_cons'><button type='button' onClick='javascript:evaluateConsent()'>I want to participate </button></span>";
document.getElementById('consent').innerHTML = HTMLtext;
}
function evaluateConsent() {
var isOK = 1;
if (document.getElementById("consAgree").checked == false) {
isOK = 0;
}
if (isOK == 0) {
alert('Please make sure you have confirmed all three conditions.nIf you do not want ot participate, return the HIT');
} else {
var HTMLtext = "Thank you! Now take a look at the example!";
document.getElementById('submit_cons').innerHTML = HTMLtext + "<hr>";
}
}
/*--MAIN--*/
function main() {
consent();
}
$(document).ready(function() {
//Ensure that form is not submitted upon pressing Enter key
$(window).keydown(function(event) {
if (event.keyCode == 13) {
event.preventDefault();
return false;
}
});
//call function to run experiment
main();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<div id="consent"></div>
看到了吗?现在它没有被检查。