1

I want to show a javascript alert when a user changes a value in a select-box. This is my code, what am i doing wrong?

aspx

<asp:DropDownList ID="ddlGroups" AutoPostBack="true" runat="server" OnSelectedIndexChanged="ddlWagons_SelectedIndexChanged"></asp:DropDownList>

aspx.cs

    protected void ddlWagons_SelectedIndexChanged(object sender, EventArgs e)
    {
        ClientScriptManager script = Page.ClientScript;
        script.RegisterStartupScript(this.GetType(), "OpenWindowScript", "alert('Clicked')");
    }
2
  • I belive you can achieve this result by using jQuery. Commented Nov 18, 2014 at 9:42
  • I don't want to use jQuery Commented Nov 18, 2014 at 9:42

3 Answers 3

2

try this

Add

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>

to your designer part

and in code part add

var ID="Whatever the data is";
ClientScript.RegisterStartupScript(this.GetType(), "script", "alert('"+ID+"');", true);

If you are using update panel

try this

var ID="Whatever the data is";
ScriptManager.RegisterStartupScript(this, this.GetType(), "script", "alert('"+ID+"');", true);
Sign up to request clarification or add additional context in comments.

Comments

2

You should be able to handle the onchange event before the postback occurs

<asp:DropDownList runat="server" onchange="alert('Clicked')" />

If you don't need a postback then don't use a server control.

3 Comments

I forgot to mention that i also want to call a javascript method when the backend method has completed, is this possible?
@TobiasOlofsson so you need the postback? Are you running something at the server-side and then need to callback into the client?
@TobiasOlofsson after back end code completes you can use RegisterStartupScript for adding a script.
2

Have you tried

<asp:DropDownList ID="ddlGroups" AutoPostBack="true" runat="server" OnSelectedIndexChanged="ddlWagons_SelectedIndexChanged" clientIdMode="static"></asp:DropDownList>

and in JS:

document.getElementById("ddlGroups").addEventListener("change", function(){
    alert("new value: " + this.options[this.selectedIndex].value);
});

4 Comments

I forgot to mention that i also want to call a javascript method when the backend method has completed, is this possible?
You mean an alert? Have you looked into ajax calls?
Uncaught TypeError: Cannot read property 'addEventListener' of null
Have you used clientIdMode="static"?

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.