Rajaram Shelar
Rajaram Shelar

Reputation: 7877

Prevent postback if particular value is selected in dropdown

I have a drop down with Autopostback property true, I want, If select Select Week option then it should not postback else it should post back. Below are the function.

JAVASCRIPT

function OnWeekChange() {
        var value = $("#DropDownListWeeks option:selected").val();
        if (value == "-1")
         return false; 
        else return true;
    }

ASPX

 <asp:DropDownList ID="DropDownListWeeks" runat="server" Height="23px" Width="252px"
                    OnSelectedIndexChanged="DropDownListWeeks_SelectedIndexChanged" AutoPostBack="true" ClientIDMode="Static"
                    AppendDataBoundItems="true"  onchange="return OnWeekChange();"> 
                </asp:DropDownList>

.CS

 weeks = client.GetWeeks(true);
        foreach (Roaster_Week week in weeks)
        {
            //Add weeks in the dropdowns with formatting 
            DropDownListWeeks.Items.Add(new ListItem(string.Format("{0:MMM d, yyyy}", week.StartDate) + " - " + string.Format("{0:MMM d, yyyy}", week.EndDate),week.WeekID.ToString()));
        }
        client.Close();
        DropDownListWeeks.Items.Insert(0, new ListItem("Select Week","-1"));

Here in my case post back is not happening at all even when I select value other than -1 .When I tried with Jquery it postbacks for all the values, why such behavior occur? Can you please provide the appropriate solution for my scenario.

Upvotes: 3

Views: 9100

Answers (2)

sp_m
sp_m

Reputation: 2707

I was having similar problem however i solved using this code.it has worked for me.

function OnWeekChange() {
            var value = $("#DropDownListWeeks option:selected").val();
            if (value == "-1")
             return false; 
            else {
             __doPostBack(value , '');
            }
         }




<asp:DropDownList ID="DropDownListWeeks" runat="server" Height="23px" Width="252px"
                        OnSelectedIndexChanged="DropDownListWeeks_SelectedIndexChanged" AutoPostBack="true" ClientIDMode="Static"
                        AppendDataBoundItems="true"  onchange="return OnWeekChange();"> 
                    </asp:DropDownList>

Upvotes: 3

शेखर
शेखर

Reputation: 17614

Remove onchange="return OnWeekChange();" and add the function below it will work.

 $(document).ready(function () {
        $("#DropDownListWeeks").change(function () {
            var value = $("#DropDownListWeeks option:selected").val();
            alert(value);
            if (value == "-1")
                return false;
            else
                return true;
        });
    });

Upvotes: 0

Related Questions