Cannot read property 'style' of null

Hi I am trying to hide a div when the page loads and display/hide it when a checkbox is checked/unchecked. This is my code:

<asp:CheckBox ID="cb1" runat="server" Text="CB" />

<div runat="server" id="div1" style="display:none">
</div>

And here is the javascript:

window.onload = function () {
    $('#cb1').change(function () {
        display('div1');
    })
}

function display(id) {
    var traget = document.getElementById(id);
    if (traget.style.display == "none") {
        traget.style.display = "block";
    } else {
        traget.style.display = "none";
    }
}

The error i get is this:

Uncaught TypeError: Cannot read property 'style' of null

This is the last version of my code. I have already tryed stuff like:

document.getElementById('div1').style.display="block";
$('#div1').hide();

… and many other options.

The result is the same. Please help

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

You are using runat="server" so try this

<%= div1.ClientID %> 

to get the Id of the div and then you can call you function like this

display('<%= div1.ClientID %>');

or use clientidmode="static" in the markup

<div runat="server" id="div1" style="display:none" clientidmode="static">
</div>

Solution 2

function display(id) {
    if ($('#'+id).css('display') === 'none') {
        $('#'+id).show();
    } else {
        $('#'+id).hide();
    }
}

Solution 3

Try this

window.onload = function () {
    $('#<%= cb1.ClientID %>').change(function () {
        display('<%= div1.ClientID %>');
    })
}

function display(id) {
   $('#'+id).toggle();
}

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply