KyleMit
KyleMit

Reputation: 29919

Execute JavaScript from ASP.NET Server on Page Load

I need to call the following code to render a combox box using JQuery's UI library:

//renders combobox element with JQueryUI library
function renderComboBox() {
    $("#combobox").combobox();
}

I can execute it just fine when I include the following js in the header:

//when doc is ready calls into function to render combobox
$(function() {
    renderComboBox();
});

However, based on conditions available at load time, I either need to decide to run or not run the code. I'd like to do that with something similar to the following:

Private Sub Page1_Load(sender As Object, e As EventArgs) Handles Me.Load
    If .... Then
        ClientScript.RegisterStartupScript(Me.GetType, _ 
            "RenderCombo", "renderComboBox();", True)
    End If
End Sub

But it doesn't seem to be working. Any thoughts?

Update: Here's a jsFiddle to demonstrate what I'm trying to do, but it's not super helpful because it doesn't help run through any of the ASP.NET specific code.

Upvotes: 2

Views: 4403

Answers (1)

Darren Wainwright
Darren Wainwright

Reputation: 30727

Because it's all relying on JQuery, you need to make sure your renderComboBox() only fires when the page is ready, So add $(function() { }) code to the code your outputting on your page_load

What is currently happening is your page loads, and the renderComboBox() fires right away - and it will be firing before any of your JQuery or UI is ready.

So try modifying your Javascript to this:

   ClientScript.RegisterStartupScript(Me.GetType, _ 
        "RenderCombo", "$(function() { renderComboBox();})", True)

Upvotes: 3

Related Questions