Reputation: 5143
I have an asp.net page and when a textbox is empty I need to hide the whole page from code behind. The problem is I have javascript and jquery code that is executed on document ready and gets data from some page controls and since the controls are not rendered this code fails and throws an exception.
At code behind i hide the whole page
// allPageTable is an html table
// with runat=server
this.allPageTable.Visible = false;
At Javascript I check if a textbox is null, if not so I run the code, else i don't. But mytxt
is not defined so it enters into the if
and fails.
if ($('#myTxt') != null) {
// My JQUERY / JS CODE
var data = $('#anotherTxt').val(); // Fails cause anotherTxt is not rendered
}
So I need a way to avoid javascript execution when the page is not rendered.
Upvotes: 1
Views: 181
Reputation: 8949
You could place your javascript code inside a Placeholder control and then set the visibility of that control the same way you set it for the html table. This way your script will not end up on the page. It needs some extra care to avoid "broken usages" of functions/variables but it's a general solution.
<table id="allPageTable" runat="server">
...
</table>
<%= "<script type=\"text/javascript\" language=\"javascript\">" %>
<asp:PlaceHolder runat="server" ID="PlaceholderJS">
javascript code here
</asp:PlaceHolder>
<%= "</script>"%>
.
this.allPageTable.Visible = PlaceholderJS.Visible = false;
Upvotes: 0
Reputation: 9055
var i = 0;
var interval = setInterval(function () {
i = i + 1;
if(typeof($('#myTxt')) != 'undefined') {
// do your stuff
clearInterval(interval);
}
}, 1000);
Don't if it's best approach, maybe someone else will post better one...
Upvotes: 0
Reputation: 219
First of all, You need this script executed on "documentReady", "onLoad" is not so necessary. To check if checkbox exists or not, You can use $('#myTxt').length > 0
because everything which is returned from jQuery selector mechanism is represented in array of elements, even if its one html element.
$(window).load
executes after everything is loaded and html page has been rendered with css included. If your script will work on windows load then you'll obtain some "blink" effect. (disappear after everything is rendered)
Upvotes: 1
Reputation: 148110
The selector $('#myTxt')
will not return null when you control with id, myTxt, does not exists. You need to check the length
of object returned by selector.
if ($('#myTxt').length > 0) {
// My JQUERY / JS CODE
var data = $('#anotherTxt').val(); // Fails cause anotherTxt is not rendered
}
Upvotes: 3