1

I am trying to pass an asp.net button control's id to a javascript function. When I call the js function start_time, the text of the button needs to change. I have done a lot of research and Im still not able to get it to work. Any help or advice is much appreciated. Below is the code I have.

<asp:Button ID="btnStart" runat="server" Text="OK" />

            $("#btnStart").click(function () {
            start_time("btnStart");
        });

            function start_time(controlStart) {
            var a = document.getElementById(controlStart);
            a.innerHTML = "Start";
        }
user1288906
  • 419
  • 2
  • 13
  • 25

3 Answers3

1
<asp:Button ID="btnStart" ClientIDMode="Static" runat="server" Text="OK" />

$("#btnStart").click(function () {
    start_time("btnStart");
});

function start_time(controlStart) {
    var a = document.getElementById(controlStart);
    a.innerHTML = "Start";
}

If you set ClientIDMode1 to static, it should work. http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientidmode(v=vs.110).aspx

Ray Cheng
  • 12,230
  • 14
  • 74
  • 137
0

The easiest way I've found to select ASP.net controls at the client is like this...

$("[ID$=btnStart]").click(function() {
    start_time(this);
});

In this code you pass the button into the function start_time, so you don't need to search the DOM for it...

function start_time(control) {
    control.innerHTML = "Start";
}

Due to the prefixing of IDs that ASP.net does to controls, the ID can change from page to page, in different contexts. That selector basically selects every element whose ID ends with btnStart.

There are other ways, using ClientID for example, but that can mean mixing ASP with JS files, depending on where your script is actually running.

If this script is running directly on the page, rather than from an included js file then you can do the following...

$("#<%= btnStart.ClientID %>").click(function() {
    start_time(this);
});

That will select the button by the ID it is given when the page is parsed on the server.

Reinstate Monica Cellio
  • 25,975
  • 6
  • 51
  • 67
0

@Archer answer is almost correct but you should use ClientID like this..!!

 $('#' + '<%= btnStart.ClientID %>').click(function() {
start_time(this);
});
Sajad Karuthedath
  • 14,987
  • 4
  • 32
  • 49