locked
Invoke external javascript function in visual web part RRS feed

  • Question

  • Hi,

    How to invoke a javascript function in visual web part.

    I have added a layouts folder in which i have the external javascript function.

    In the UI, page, i am trying to call a function which is available inside the external javascript. but i am not able to.

    This is the UI code in the user control:

    At the start of the page i have added:

    [CODE]

     

     

    <script language="javascript" type="text/javascript" src="/sites/vdev/_layouts/ChildRecord/date_picker.js" >

     

     

    </script>

    [/CODE]

    [CODE]

     

     

    <asp:TextBox ID="txtBirthDate" runat="server" ></asp:TextBox>

     

     

    <a href="javascript:show_calendar('this.txtBirthDate');">

    [/CODE]

    show_calendar is the function name available in the external javascript.

    How to call a external javascript function?

    Thank you

    Thursday, December 9, 2010 6:15 PM

Answers

  • For starters you should be registering your javascript via the Page's properties in your code behind, rather than adding <script> tags to your markup. That way the file is only included once, even if there are multiple instances of the web part on a page:

    [Code behind]

    this.Page.ClientScript.RegisterClientScriptInclude(this.GetType(), "DatePicker", "/_layouts/ChildRecord/date_picker.js");
    

    Secondly, you can't use qualifiers like 'this.txtBirthDate' directly in your markup and expect JavaScript to understand it - the JS will run client side, and the C# will run server side. The ID property of your TextBox is a server side property - if you want to get the ID that is rendered in the textbox's <input> tag you need to access the ClientId property. Start by adding the hyperlink in your markup:

    [ASPX markup]

    <asp:HyperLink ID="showCalendarLink" runat="server" Text="Show calendar" />
    

    Then in your code behind set the hyperlink's NavigateUrl property:

    [Code behind]

    showCalendarLink.NavigateUrl = String.Format("javascript:show_calendar('{0}')", txtBirthDate.ClientID);
    

    In your rendered markup the link href will appear like this href="javascript:show_calendar('ctl00_PlaceHolderMain_txtBirthDate')", so in your JS function you'll have something like this:

    function show_calendar(textBoxId) {
     var textBox = document.getElementById(textBoxId);
     var textBoxValue = textBox.value;
     alert(textBoxValue);
    }
    

    If this doesn't work then there's a typo somewhere! Hope this helps...

    Sam

     

    • Proposed as answer by samdv1982 Friday, December 10, 2010 12:47 AM
    • Marked as answer by Wayne Fan Thursday, December 16, 2010 1:51 AM
    Friday, December 10, 2010 12:47 AM