简体   繁体   中英

Force javascript to run on aspx page load

I have a aspx page with some databound controls. One of them is a checkbox. If this checkbox is checked then it should show a div, else hide it. It works great when I click/unclick the box. BUT, when the page loads initially the div ALWAYS shows up until I check/uncheck the checkbox. How can I fix this so that if the databound checkbox is not checked then when the page loads the div is hidden?

<script type="text/javascript">
   function hideDiv(obj) {
        if (obj.checked == true) {
            document.getElementById("divHome").style.display = 'block';
        }
        else {
            document.getElementById("divHome").style.display = 'none';

        }
    }
</script>
<asp:CheckBox ID="cbMycb" runat="server" ClientIDMode="Static" onClick="hideDiv(this);"
    Checked='<%# Bind("MyField") %>' />
<br />
<div id='divHome'>
        STUFF INSIDE THE DIV
</div>

You can either run the hideDiv function when the content is loaded as Amit Joki stated.

    window.onload =function(){
    hideDiv(document.getElementById('cbMycb'));

But, this solution might present a little issue, you might see the div flickers when the page loads if the div is visible. To solve it just make sure the div is not visible by default by adding some css style...

#divHome{
    display: none;
}

Another approach would be using a conditional databinding expression to set the div's visibility...

<div id='divHome' style='<%# "display:" +  ((bool)Eval("MyField") ? "block" : "none") %>'>
        STUFF INSIDE THE DIV
</div>

Hope it helps

Just call your function once outside.

<script type="text/javascript">
   function hideDiv(obj) {
        if (obj.checked == true) {
            document.getElementById("divHome").style.display = 'block';
        }
        else {
            document.getElementById("divHome").style.display = 'none';

        }
    }
    window.onload =function(){
        hideDiv(document.getElementById('cbMycb'));
    }
</script>

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