1

I am fairly new to js and am having trouble when trying to call a js function from my codebehind.

C#:

protected void GridView3_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            tbListOfCountries.Text = GridView3.SelectedRow.Cells[1].Text;
            Page.ClientScript.RegisterStartupScript(this.GetType(), "test", "test()", true);   
        }

JavaScript:

 function test() {
       alert("test");     
    }

And the Unexpected Identifier error:

//<![CDATA[
test()Sys.Application.add_init(function() {
    $create(Sys.Extended.UI.TabPanel, {"headerTab":$get("__tab_TabContainer1_TabPanel1"),"ownerID":"TabContainer1","wasLoadedOnce":true}, null, {"owner":"TabContainer1"}, $get("TabContainer1_TabPanel1"));
});

Any insights?

1

2 Answers 2

3

It looks like your script test() isn't syntactically correct. Try replacing with test();

Sign up to request clarification or add additional context in comments.

3 Comments

I have tried that as well, but then I get the ReferenceError:test is not defined
Well, you do actually need a method called test() in one of your script resources or in a <script> block in order for it to work. E.g., if you replace test(); with alert('boo!'); it should run
Excellent pick ';` missing
1

If you're running this in an UpdatePanel you may encounter some issues (especially on PostBack). I find this version works best:

Control sender = MyUpdatePanel;
string javaScript = "alert('Hello');"; 
ScriptManager.RegisterStartupScript(sender, sender.GetType(), Guid.NewGuid().ToString(), javaScript, true);

You'll need a ScriptManager tag on the page:

<asp:ScriptManager ID="MyScriptManager" runat="server" />

2 Comments

I've tried your example and it works for the alert, however, when I try to set string javascript to the name of my function, it is no longer firing. Am i missing something?
Your function maybe out of context, is it at the top of the page or at the bottom? And is it nested in an UpdatePanel? Press F12 on your browser and see the Console for javascript errors this will give you a better indication of that's gone wrong.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.