0

I am trying to validate a drop down inside a gridview on a button click. If the drop down has no selection then i want to fire the javascript but the code is not firing at all. I am not sure what am i doing wrong here so please help. thanks. Here is the button code in the aspx file:

<asp:Button ID="btnSubmit" runat="server" Text="Submit" Width="183px" Visible="true"
                onclick="btnSubmit_Click" 
                OnClientClick="return validate();" 
                Font-Bold="True" Font-Size="Medium" Height="30px" 
                style="margin-right: 1px; margin-left: 185px;" ForeColor="#336699" />

here is the javascript in the head section of my page:

<script type="text/javascript">
          function validate() {
              var flag = true;
              var dropdowns = new Array(); //Create array to hold all the dropdown lists.
              var gridview = document.getElementById('<%=GridView1.ClientID%>'); //GridView1 is the id of ur gridview.
              dropdowns = gridview.getElementsByTagName('--'); //Get all dropdown lists contained in GridView1.
              for (var i = 0; i < dropdowns.length; i++) {
                  if (dropdowns.item(i).value == '--') //If dropdown has no selected value
                  {
                      flag = false;
                      break; //break the loop as there is no need to check further.
                  }
              }
              if (!flag) {
                  alert('Please select value in each dropdown');
              }
              return flag;
          }
</script>

here is my drop-down in the aspx:

<ItemTemplate>
  <asp:Label ID="lblAns" runat="server" Text='<%# Eval("DDL_ANS")%>' Visible="false"></asp:Label>
 <asp:DropDownList ID="ddl_Answer" runat="server" AutoPostBack="false">
  </asp:DropDownList>
 </ItemTemplate>

here is the code behind for the dropdown

 ddl_Answer.DataSource = cmd1.ExecuteReader();
                    ddl_Answer.DataTextField = "DD_ANSWER";
                    ddl_Answer.DataValueField = "DD_ANSWER";
                    ddl_Answer.DataBind();
ddl_Answer.Items.Insert(0, new ListItem("--"));

1 Answer 1

2

How are you trying to select the dropdown using javascript. You probably want this

dropdowns = gridview.getElementsByTagName('select');
Sign up to request clarification or add additional context in comments.

Comments

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.