javascript - GetElementById of ASP.NET Control keeps returning 'null' -
i'm desperate having spent on hour trying troubleshoot this. trying access node in dom created asp.net control. i'm using same id , can see match when looking @ html source code after page has rendered. here's [modified according suggestions, still not working] code:
asp.net header
<asp:content id="headercontent" runat="server" contentplaceholderid="headcontent"> <script type="text/javascript"> $(document).ready( var el = document.getelementbyid('<%= txtbox.clientid %>'); el.onchange = alert('test!!'); ) </script> </asp:content>
asp.net body
<asp:textbox id="txtbox" runat="server"></asp:textbox>
resulting javascript & html above
<script type="text/javascript"> $(document).ready( var el = document.getelementbyid('maincontent_txtbox'); el.onchange = alert('test!!'); ) </script> ... <textarea name="ctl00$maincontent$txtbox" id="maincontent_txtbox"></textarea>
i can assume script loading before control id has been resolved, yet when @ timeline chrome's "inspect element" feature, appears not case. when created regular textarea box test , implement identical code (different id of course), alert box fires.
what on earth missing here? driving me crazy >.<
edit: wierd code works, on initial page load; firing onload rather onchange. jquery says .ready doesn't work apparently. ugh!!
$(document).ready(function() { document.getelementbyid('<%= txtbox.clientid %>').onchange = alert('working!'); })
assuming rendered markup appear in order, problem element doesn't yet exist @ time javascript attempting locate it.
either move js below element (preferably right @ end of body) or wrap in jquery's document ready event handler.
update:
in response edits, you're there (as others have mentioned) need assign function onchange event, not return result of alert()
. this:
$(document).ready(function() { // might use jquery attach event since you're using // document ready event. $('#<%= txtbox.clientid %>').change(function() { alert('working!'); }); });
by writing onchange = alert('working');
, asking javascript assign result of alert()
method onchange property. that's why executing on page load, never in response onchange event (because hadn't assigned function run onchange).
Comments
Post a Comment