Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

When you are coding in an aspx page you can do something like this:

<html>
  <head>
    <script type="text/javascript">
      $(document).ready(function () {
        var chkEnable = $get("<%= chkEnable.ClientID %>");
        alert(chkEnable);
      });
    </script>
  </head>
  <body>
    <form runat="server">
      <asp:CheckBox ID="chkEnable" runat="server" />
    </form>
  </body>
</html>

But the only way I have found to use javascript in a web part is to use a ScriptLink that imports the file. Example:

<SharePoint:ScriptLink ID="ScriptLink5" runat="server" Name="myPorject/js/myCustomScript.js" Localizable="false" LoadAfterUI="true"/>
<asp:CheckBox ID="chkEnable" runat="server" />

Is there any way that I could reproduce the functionality from my first example in a web part? Anything that I do must be able to be installed entirely through a wsp onto a system that I have no other access to. Any solution must be implemented entirely through the wsp.

share|improve this question
    
by wsp do you mean sandbox or farm solutions? –  djeeg Apr 18 '11 at 5:17
    
sorry, farm solutions. –  Abe Miessler Apr 18 '11 at 15:07

2 Answers 2

up vote 1 down vote accepted

ScriptLink is the recommended way if you're using a Farm solution. You can also add inline scripts to the WP (not the best way) or manually add your script tags to the WP. Also take use of the Script-On-Demand (SOD) features that is available in SP2010: http://blogs.msdn.com/b/sharepointdev/archive/2011/01/27/loading-script-in-sharepoint-2010.aspx

To make the variable "dynamic"; add inline JS code to your Web Part and just set the variable name/value there. Then use an external JS file to host your logic

share|improve this answer
    
Ok, so the external JS file will have access to that variable once I create it? Do I need to load them in a specific order or anything? –  Abe Miessler Apr 18 '11 at 15:07
    
If the variable is defined inline, then it will always be available before any external JS files. Use the SOD features to call your external script from inline code, so that you are sure that the file is loaded and ready. –  Wictor Wilen MCA MCM MVP Apr 18 '11 at 19:57

What about writing out to a literal using code behind? The can be a user control in a web part, which would be deployed as a wsp.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.