...

View Full Version : can't access web control from javascript function



gib65
03-23-2012, 05:20 PM
This is a question more about an ASP.NET web application, but javascript is involved, so I'm hoping some javascript gurus can assist me.

I'm working with a web application that needs to get access to an ASP.NET web control (a button) in javascript. The problen is that since the control is run on the server, javascript can't access it in the standard way (i.e. document.getElementById(controlId); ).

I've actually solved this problem before in a different application, but my solution there doesn't seem to work here for some reason.

I have this in an aspx file:



<script...>

...

function myfun()
{
var b = document.getElementById("<%=SaveButton.ClientID%>");
alert(b);
}

</script>

...

<asp:Button ID="SaveButton" Text="save" OnClientClick="myfun()" ClientIDMode="Static" runat="server" UseSubmitBehavior="False" />


I have a designer class in which the button is declared (and therefore exists in the server-side codebehind):



protected global::System.Web.UI.WebControls.Button SaveButton;


But when I click on my button, the alert box says "null".

Why am I not able to get my button in the javascript function?

Some things to note:

*The button exists within a content tag:



<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">


*I'm working within Visual Studios 2008.

Old Pedant
03-23-2012, 08:49 PM
Bring up the page in the browser.

Click on the VIEW menu of the browser.

Click on the SOURCE or PAGE SOURCE menu item.

Now look at the HTML that your ASP.NET page is generating.

Find your button in that HTML.

If that doesn't help you with the JavaScript, then show the relevant HTML here. Maybe 10 or so lines of HTML on either side of the button in question.

Old Pedant
03-23-2012, 08:52 PM
Ummm...but there is likely a much simpler way.

I just noticed that you are trying to get the reference to the SAME BUTTON that was clicked on, right?

So...


<asp:Button ID="SaveButton" Text="save" OnClientClick="myfun(this)"
ClientIDMode="Static" runat="server" UseSubmitBehavior="False" />


And then:


function myfun( theClickedOnButton )
{
// example code only:
alert( "id of that button is " + theClickedOnButton.id
+ "\nvalue of that button is " + theClickedOnButton.value );
}

gib65
03-24-2012, 07:28 PM
Both solutions work! Thanks to both of you!

Old Pedant
03-24-2012, 11:16 PM
Both solutions work! Thanks to both of you!

Sadly, there is now only one of us. My brother was an only child.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum