ANP
ANP

Reputation: 15607

Jquery not working when externalized it to js file

$(function() { $('#<%=btnAdd.ClientID%>').click( { code }); });

The above jquery code I have written inside the aspx code and it works fine. But when I tried to externalize the code by creating one js file and transferring the internal code to that file it does not work. I mean when I write the same code in an external file and add that to aspx page it does not work.Can any one help me to solve the problem ?

Upvotes: 0

Views: 750

Answers (3)

ANP
ANP

Reputation: 15607

It can be done by passing the value in a variable from aspx page. Like: In aspx page:

<script language="javascript" type="text/javascript">
var btnAdd = '<%= btnAdd.ClientID %>';
<script>

In externalized js file:

$(function() 
{ 
   $('#' + btnAdd).click( {
        ----code---- 
    }); 
});

Upvotes: 0

Andy Rose
Andy Rose

Reputation: 16974

<%=btnAdd.ClientID%> won't be parsed by the asp.net worker process so it won't be replaced by the client id of the button. This code needs to be in your aspx page.
The alternative is to select your button a different way e.g. class, input[type="submit"] etc.

$(function() { $('input[type="submit"]').click( { code }); });

Upvotes: 2

Nick Craver
Nick Craver

Reputation: 630349

That's because <%=btnAdd.ClientID%> is literally in the file, it's not an evaluated server tag resulting in something like container_btnAdd, instead give the button a class, like this:

<asp:Button id="btnAdd" runat="server" CssClass="btnAdd" Text="Add" />

Then use that class in your selector, so the ID won't matter, like this:

$(function() { 
  $('.btnAdd').click({ code }); 
});

Upvotes: 1

Related Questions