复选框未定义的行为

时间:2018-01-29 00:46:55

标签: javascript html

我遇到单选按钮和复选框的问题。

请参阅下面的代码段。这个想法如下:当用户推动'我想参与'按钮,代码应该检查用户是否选中了复选框,如果没有则提醒。

警报在需要时引发,但当我关闭它时,即使不是之前,该复选框也会被标记。为什么会这样?

非常感谢!



<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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您正在关闭label标记,如下所示:<\label>,对此</label>

的更改不正确

&#13;
&#13;
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();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<div id="consent"></div>
&#13;
&#13;
&#13;

请参阅?现在它没有被检查。