Prevent postback if selected value is selected from dropdown list

I have a dropdown property Autopostback true, I want, if an Select Week

option is selected , then it should not return back, it should send a message back. Following are the functions.

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 doesn't happen at all, even when I select a value other than -1

. When I tried with Jquery

it was returning all values, why is this behavior happening? Can you provide an appropriate solution for my scenario.

+3


source to share


2 answers


I had a similar problem, however I resolved to use this code. This 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>

      

+3


source


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;
        });
    });

      

0


source







All Articles