简体   繁体   中英

Displaying checkbox state on page load

I assembled some code that checks the state of a checkbox and then displays the corresponding message as a string. The default state of the checkbox is "unchecked", but when I reload the page there's no message displaying "Unchecked", it will work as intended once I check the checkbox and uncheck. I want the state to display on page load in a nutshell, not on-change. Here's the code:

<html>
<head>
</head>
<body>

<input type="checkbox" id="checkBox" />
<div id="text"></div>

<script type="text/javascript">
var getId = document.getElementById('text'),
    checkbox = document.getElementById('checkBox');

function checkState(){
    text.innerHTML = checkbox.checked ? "Checkbox is checked" : "Checkbox is empty";
}
checkbox.onchange = checkState;
</script>

</body>
</html>

Right now you're running the function as an onchange handler. That is the event which fires when the state of the checkbox changes, as you have seen. You said:

I want the state to display on page load in a nutshell, not on-change.

Then the fix should be pretty darn obvious: change the checkbox.onchange to a window.onload .

You just need to call your own function in addiction to set it as the checkbox onchange event.

Since you're executing the script on the end of the body, it only gets executed when you already have access to the DOM, you just need to call checkState() after it's definition.

<html>
<head>
</head>
<body>

<input type="checkbox" id="checkBox" />
<div id="text"></div>

<script type="text/javascript">
var getId = document.getElementById('text'),
    checkbox = document.getElementById('checkBox');

function checkState(){
    text.innerHTML = checkbox.checked ? "Checkbox is checked" : "Checkbox is empty";
}
checkbox.onchange = checkState;
checkState();
</script>

</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM