如何自动选中复选框并在选中时自动显示结果



这是我的复选框代码,我想让它自动检查,并在检查时显示结果

<!DOCTYPE html>
<html>
<body>
<p>Display some text when the checkbox is checked:</p>
<label for="myCheck">Checkbox:</label> 
<input type="checkbox" id="myCheck" onclick="myFunction()">
<p id="text" style="display:none">Checkbox is CHECKED!</p>
<script>
function myFunction() {
var checkBox = document.getElementById("myCheck");
var text = document.getElementById("text");
if (checkBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
}
</script>
</body>
</html>

您可以在加载内容时添加一个函数,然后将复选框设置为选中,最后调用myFunction方法

<!DOCTYPE html>
<html>
<body onload="init()">
<p>Display some text when the checkbox is checked:</p>
<label for="myCheck">Checkbox:</label> 
<input type="checkbox" id="myCheck" onclick="myFunction()">
<p id="text" style="display:none">Checkbox is CHECKED!</p>
<script>
function init(){
var checkBox = document.getElementById("myCheck");
checkBox.checked = true;
myFunction();
}
function myFunction() {
var checkBox = document.getElementById("myCheck");
var text = document.getElementById("text");
if (checkBox.checked == true){
text.style.display = "block";
} else {
text.style.display = "none";
}
}
</script>
</body>
</html>

$('#myCheck').prop('checked',true);
myFunction();
function myFunction() 
{
if($('#myCheck').prop("checked") == true)
{
$('#text').show();
}
else
{
$('#text').hide();
}
}
<!DOCTYPE html>
<html>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Display some text when the checkbox is checked:</p>
<label for="myCheck">Checkbox:</label> 
<input type="checkbox" id="myCheck" onclick="myFunction()">
<p id="text">Checkbox is CHECKED!</p>
</body>
</html>

最新更新