Validating a listbox using javascript

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • laks2886
    New Member
    • Dec 2008
    • 6

    Validating a listbox using javascript

    can anybody tell me how do u validate a listbox to select atleast one item from it. I have a listbox within the template field of a grid view. and these listboxes can vary from 1 to 4. how can i know how many listboxes are present so that i can loop in javascript.
  • acoder
    Recognized Expert MVP
    • Nov 2006
    • 16032

    #2
    Welcome to Bytes!

    I assume you mean a multiple select. You can validate it by looping over the options (see example) and checking how many are selected (check the selected property).

    To get all the list boxes in a page, use document.getEle mentsByTagName( "select") and loop over the resulting array.

    Comment

    • laks2886
      New Member
      • Dec 2008
      • 6

      #3
      thanks for the reply.. i have drop down and lsit boxes in my page.. these listboxes are dynamic and can vary from 1 to 4.

      as u said i have used document.getEle mentsByTagName( "select") to get all the references.. this is working fine for the dropdown, when it comes to list box ... instead of selecting the labeldesc of the lisbox it takes the values of the list box.

      Comment

      • acoder
        Recognized Expert MVP
        • Nov 2006
        • 16032

        #4
        Can you show the code for the list box. How does it differ from a drop-down?

        Comment

        • laks2886
          New Member
          • Dec 2008
          • 6

          #5
          This is the Java script functin for validating the drop down.. listbox n text box...

          [code=javascript]
          function ValidateSave()
          {
          var lblSelectClient = document.getEle mentById('<%=dd lSelectClient.C lientID%>');
          if(lblSelectCli ent.selectedInd ex==0)
          {
          alert('Please select a client');
          return false;
          }

          var ddlSelectHierar chy = document.getEle mentById('<%=dd lSelectHierarch y.ClientID%>');
          if(ddlSelectHie rarchy.selected Index==0)
          {
          alert('Please select a hierarchy');
          return false;
          }

          var hdMode = document.getEle mentById('<%=hd Mode.ClientID%> ');
          var isSelected = false;
          var hasList = false;
          var strLevel="";
          //if(hdMode.value ="HierEdit")
          {
          var dropdownReferen ces = document.getEle mentsByTagName( "select");

          if(dropdownRefe rences !=null)
          {
          if(dropdownRefe rences.length != null)
          {
          for (i = 0; i <dropdownRefere nces.length-1; i++)
          {
          if(dropdownRefe rences[i].id.search("Lst HierA")==-1)
          {
          if(dropdownRefe rences[i].selectedIndex= =0)
          {
          var level = document.getEle mentById(replac e(dropdownRefer ences[i].name.replace(" ddlLevel","lblL evelDesc"),"$", "_")).innerText ;
          if(level.search ("Select")!=-1)
          {
          level=level.rep lace("Select ","");
          }

          alert('Please select a value for '+level);
          return false;
          }
          }
          else
          {
          hasList = true;
          strLevel = document.getEle mentById(replac e(dropdownRefer ences[i].name.replace(" lstHierA","lblL evelDesc"),"$", "_")).innerText ;
          if(strLevel!="" )
          {
          strLevel=strLev el.replace("Sel ect ","");
          }
          for(j=0;j<dropd ownReferences[i].length;j++)
          {
          if(dropdownRefe rences[i].options[j].selected)
          {

          isSelected=true ;
          break;
          }
          }
          }
          }
          }
          }

          var inputReferences = document.getEle mentsByTagName( "input");

          if (inputReference s != null)
          {
          if (inputReference s.length != null)
          {
          for (i = 0; i <= inputReferences .length-1; i++)
          {
          if (inputReference s[i].type == 'text')
          {
          if (inputReference s[i].value == null || inputReferences[i].value == "")
          {

          var level = document.getEle mentById(replac e(inputReferenc es[i].name.replace(" txtEnterNewLeve l","lblLevelDes c"),"$","_")).i nnerText;
          if(level.search ("Select")!=-1)
          {
          level=level.rep lace("Select ","");
          }
          else
          {
          level = document.getEle mentById(replac e(inputReferenc es[i].name.replace(" txtLeafNode","l blLevelDesc")," $","_")).innerT ext;
          if(level.search ("Enter")!=-1)
          {
          level=level.rep lace("Enter ","");
          }
          }

          alert('Please enter a value for '+level);
          inputReferences[i].focus();
          return false;

          }
          var Ok;
          OK=CheckLength( inputReferences[i]);
          if(!OK)
          {
          return false;
          }
          }
          }
          }
          }
          }
          if(hasList)
          {
          if(!isSelected)
          {
          if(strLevel!="" )
          {
          alert('Please select a '+strLevel);
          return false;
          }
          }
          }

          return true;
          }

          [/code]
          lstHierA is the name of the listbox
          Last edited by Frinavale; Dec 30 '08, 05:31 PM. Reason: added [code] tags

          Comment

          • acoder
            Recognized Expert MVP
            • Nov 2006
            • 16032

            #6
            OK, but what about the actual list box code (view source at the client to see how it's rendered in HTML).

            Comment

            • laks2886
              New Member
              • Dec 2008
              • 6

              #7
              Code:
              <asp:GridView ID="grdLevels" runat="server" AutoGenerateColumns="False" Width="750px" OnRowDataBound="grdLevels_RowDataBound" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal" EnableViewState="true">
                              <Columns>
                                  <asp:TemplateField HeaderText="LevelDesc" ShowHeader="False">
                                      <ItemTemplate>
                                          <asp:Label ID="lblLevelDesc" Width="150px" runat="server" Text='<%# Bind("LevelDesc") %>'></asp:Label>
                                      </ItemTemplate>
                                  </asp:TemplateField>
                                  <asp:TemplateField ShowHeader="False" HeaderText="LevelControls">
                                      <ItemTemplate>
                                          <asp:DropDownList ID="ddlLevel" Width="200px" Enabled="false" OnSelectedIndexChanged="ddlLevel_SelectedIndexChanged" runat="server" AutoPostBack="true" AppendDataBoundItems="true">
                                          <asp:ListItem Selected="True" Value="0">--Select--</asp:ListItem>
                                          </asp:DropDownList>
                                          <asp:TextBox ID="txtLeafNode" runat="server"></asp:TextBox>
                                         
                                         
                                      
                                         <div id='divList1' runat="server"  style="Z-INDEX: 102;OVERFLOW:auto; WIDTH: 247px;height:90px" >
               
                                          <asp:ListBox ID="LsthierA" SelectionMode="Multiple" Width="700px" runat="server" Rows="5" Height="10000">
                                          </asp:ListBox>
                                         
                                          </div>
              
                                          
                                           <asp:ListBox ID="lstLevel" Width="200px" Visible="false" runat="server"></asp:ListBox>
                                          <asp:HiddenField ID="hdlLevelKey" Value='<%#DataBinder.Eval(Container.DataItem,"LevelKey") %>' runat="server" />
                                          <asp:HiddenField ID="hdIsLeafNode" Value='<%#DataBinder.Eval(Container.DataItem,"IsLeafNode") %>' runat="server" />
                                          <asp:HiddenField ID="hdIsRoot" Value='<%#DataBinder.Eval(Container.DataItem,"IsRoot") %>' runat="server" />
                                          <asp:HiddenField ID="hdDDLSelection" runat="server"/>
                                          <asp:HiddenField ID="hdHierKey" runat="server"/>
                                     
                                          <asp:TextBox ID="txtEnterNewLevel" Width="195px" Visible="false" runat="server" Enabled="false"></asp:TextBox>
                                      </ItemTemplate>                      
                                  </asp:TemplateField>
                                  <asp:TemplateField HeaderText="NewLevelButton">
                                      <ItemTemplate>
                                          <asp:Button ID="btnNewLevel" OnClick="btnNewLevel_Click" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"LevelDesc") %>' />
                                      </ItemTemplate>
                                  </asp:TemplateField>
                                  <asp:TemplateField HeaderText="AttributeValueButton">
                                  <ItemTemplate>
                                      <asp:Button ID="btnAtVal" runat="server" Text="Add Attribute Value" OnClick="btnAtVal_Click" Width="118px" />
                                  </ItemTemplate>
                                  </asp:TemplateField>
                               
                              </Columns>
                              <FooterStyle BackColor="#CCCC99" ForeColor="Black" />
                              <SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
                              <PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
                              <HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
                          </asp:GridView>



              _______________ _______________ _______________ ______ Is this wat u asked for??? In the function validatesave() .. am getting the references of the items with tag select. which includes dropdowns and listboxes which vary from (0-4). 1. i want to know how many listboxes are present?? wat's happening is .. whenever i select a item(eg., ABCD) from the listbox select item... it's giving an pop up alert saying.. Please select a value for ABCD. Actually validation should happen when am not selecting from the listbox and it should be like ' Please selec a value for Item'? Please let me know wat is wrong in function validate save?
              Last edited by acoder; Jan 10 '09, 11:22 AM. Reason: Added [code] tags

              Comment

              • acoder
                Recognized Expert MVP
                • Nov 2006
                • 16032

                #8
                Originally posted by laks2886
                Is this wat u asked for?
                Almost, but not quite. What you've posted is ASP.NET code, which is not much use for JavaScript. JavaScript runs on the client-side, so it sees the client-side generated code which you should post (load the page and view source in the browser).

                PS. please remember to use [code] tags when posting code. Thanks!

                Comment

                Working...