user2030579
user2030579

Reputation: 41

Execute javascript confirm on drop down list onSelectedIndexChanged Event

I have a drop down list and I would like to invoke a javascript confirm box on the selectedindexchanged event of the drop down list. The problem is I don't know how to invoke the javascript confirm box before the execution of the C# code of the selectedindexchanged event is executed. My .aspx code is:

 OnSelectedIndexChanged ="ddlCauses_SelectedIndexChanged"

I would like to do something like:

OnSelectedIndexChanged = "return confirm('Are you sure you want to change the cause code?');"



OnSelectedIndexChanged ="ddlCauses_SelectedIndexChanged"

However I don't think I can assign the onSelectedIndexChanged to two different things...How can I allow for the javascript confirm to be executed and then the C# code executed if yes is selected?

Upvotes: 0

Views: 5243

Answers (2)

Joe
Joe

Reputation: 5487

If I understand correctly

On the server side you would populate your dropdown and setup the event handler

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            uiItems.Items.Add(new ListItem("", ""));
            uiItems.Items.Add(new ListItem("One", "One"));
            uiItems.Items.Add(new ListItem("Two", "Two"));
            uiItems.Items.Add(new ListItem("Three", "Three"));
            uiItems.Attributes.Add("onChange", "confirmfunction();");
        }
    }

    protected void ddlCauses_SelectedIndexChanged(object sender, EventArgs e)
    {
        uiText.Text = uiItems.SelectedItem.Text;
    }

On the aspx page you would have

    <asp:DropDownList runat="server" ID="uiItems" OnSelectedIndexChanged="ddlCauses_SelectedIndexChanged">
</asp:DropDownList>

<script type="text/javascript">
    function confirmfunction() {
        if (confirm("Make this change?")) {
            __doPostBack('uiItems', '');
        } 
    }
</script>

The caveat to this being that the original value of the select box isn't restored if you choose "Cancel" on the confirm prompt.

Upvotes: 0

Zeke Nierenberg
Zeke Nierenberg

Reputation: 2206

If you were to use jQuery you could do the following:

$("#yourSelectId").change(function(event){
    event.preventDefault(); //This makes the standard event not happen
    if(confirm('text'))
        //do something...
});

Upvotes: 1

Related Questions