Reputation: 333
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
Upvotes: 0
Views: 2043
Reputation: 8726
Try this
window.onload = function () {
$('#<%= cb1.ClientID %>').change(function () {
display('<%= div1.ClientID %>');
})
}
function display(id) {
$('#'+id).toggle();
}
Upvotes: 1
Reputation: 9990
function display(id) {
if ($('#'+id).css('display') === 'none') {
$('#'+id).show();
} else {
$('#'+id).hide();
}
}
Upvotes: 1
Reputation: 40970
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>
Upvotes: 4