views:

31

answers:

2

$(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 ?

+2  A: 

<%=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 }); });
Andy Rose
Would you like to explain the alternative way a more?
ANP
@ANP There is a good example of using a class shown in @Nick's answer which would probably be the best way to go. I have added an example which uses html elements in the selector which will apply to any submit buttons on the page.
Andy Rose
+1  A: 

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 }); 
});
Nick Craver
Actually the css class which is used in the btnAdd the same class is used in other buttons also.So if I do as you have suggested the jquery function will fire in all the buttons click with that css class.Can you suggest how I will avoid this?
ANP
@ANP - You can give it multiple classes, e.g. `CssClass="class1 class2 class3"` just separate with a space, you can use any of those classes as your selector, whichever is unique, for example `$(".class2")` will only bind to those with `class2`.
Nick Craver