473,785 Members | 2,801 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Validating a listbox using javascript

6 New Member
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.
Dec 24 '08 #1
7 15000
acoder
16,027 Recognized Expert Moderator MVP
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.
Dec 24 '08 #2
laks2886
6 New Member
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.
Dec 25 '08 #3
acoder
16,027 Recognized Expert Moderator MVP
Can you show the code for the list box. How does it differ from a drop-down?
Dec 29 '08 #4
laks2886
6 New Member
This is the Java script functin for validating the drop down.. listbox n text box...

Expand|Select|Wrap|Line Numbers
  1. function ValidateSave()
  2. {
  3.     var lblSelectClient                 = document.getElementById('<%=ddlSelectClient.ClientID%>');
  4.     if(lblSelectClient.selectedIndex==0)
  5.     {
  6.         alert('Please select a client');
  7.         return false;
  8.     }
  9.  
  10.     var ddlSelectHierarchy             = document.getElementById('<%=ddlSelectHierarchy.ClientID%>');
  11.     if(ddlSelectHierarchy.selectedIndex==0)
  12.     {
  13.         alert('Please select a hierarchy');
  14.         return false;
  15.     }    
  16.  
  17.     var hdMode                          = document.getElementById('<%=hdMode.ClientID%>');
  18.     var isSelected                      = false;
  19.     var hasList                         = false;
  20.     var strLevel="";
  21.     //if(hdMode.value="HierEdit")
  22.     {
  23.         var dropdownReferences = document.getElementsByTagName("select");
  24.  
  25.         if(dropdownReferences !=null)
  26.         {
  27.             if(dropdownReferences.length != null)
  28.             {
  29.                 for (i = 0; i <dropdownReferences.length-1; i++)
  30.                 {
  31.                     if(dropdownReferences[i].id.search("LstHierA")==-1)
  32.                     {
  33.                         if(dropdownReferences[i].selectedIndex==0)
  34.                         {
  35.                                  var level = document.getElementById(replace(dropdownReferences[i].name.replace("ddlLevel","lblLevelDesc"),"$","_")).innerText;
  36.                                 if(level.search("Select")!=-1)
  37.                                 {
  38.                                     level=level.replace("Select ","");
  39.                                 }
  40.  
  41.                                 alert('Please select a value for '+level);
  42.                                 return false;                     
  43.                         }
  44.                     }
  45.                     else
  46.                     {
  47.                         hasList = true;
  48.                         strLevel = document.getElementById(replace(dropdownReferences[i].name.replace("lstHierA","lblLevelDesc"),"$","_")).innerText;
  49.                         if(strLevel!="")
  50.                         {
  51.                             strLevel=strLevel.replace("Select ","");
  52.                         }
  53.                         for(j=0;j<dropdownReferences[i].length;j++)
  54.                         {
  55.                             if(dropdownReferences[i].options[j].selected) 
  56.                             {
  57.  
  58.                                 isSelected=true;
  59.                                 break;
  60.                             }
  61.                         }
  62.                     }
  63.                 }
  64.             }
  65.         }
  66.  
  67.         var inputReferences= document.getElementsByTagName("input");
  68.  
  69.            if (inputReferences != null)
  70.         {
  71.             if (inputReferences.length != null)
  72.             {
  73.                 for (i = 0; i <= inputReferences.length-1; i++)
  74.                 {
  75.                     if (inputReferences[i].type == 'text')
  76.                     {
  77.                         if (inputReferences[i].value == null || inputReferences[i].value == "")
  78.                         {
  79.  
  80.                              var level = document.getElementById(replace(inputReferences[i].name.replace("txtEnterNewLevel","lblLevelDesc"),"$","_")).innerText;
  81.                             if(level.search("Select")!=-1)
  82.                             {
  83.                                 level=level.replace("Select ","");
  84.                             }
  85.                             else
  86.                             {
  87.                                 level = document.getElementById(replace(inputReferences[i].name.replace("txtLeafNode","lblLevelDesc"),"$","_")).innerText;
  88.                                 if(level.search("Enter")!=-1)
  89.                                 {
  90.                                     level=level.replace("Enter ","");
  91.                                 }
  92.                             }
  93.  
  94.                             alert('Please enter a value for '+level);
  95.                             inputReferences[i].focus();
  96.                             return false;
  97.  
  98.                         }
  99.                         var Ok;
  100.                         OK=CheckLength(inputReferences[i]);
  101.                         if(!OK)
  102.                         {
  103.                             return false;
  104.                         }
  105.                     }
  106.                 }            
  107.             }             
  108.         }
  109.     }
  110.     if(hasList)
  111.     {
  112.         if(!isSelected)
  113.         {
  114.             if(strLevel!="")
  115.             {
  116.                 alert('Please select a '+strLevel);
  117.                 return false;
  118.             }
  119.         }
  120.     }
  121.  
  122.     return true;
  123. }
  124.  
  125.  
lstHierA is the name of the listbox
Dec 30 '08 #5
acoder
16,027 Recognized Expert Moderator MVP
OK, but what about the actual list box code (view source at the client to see how it's rendered in HTML).
Dec 31 '08 #6
laks2886
6 New Member
Expand|Select|Wrap|Line Numbers
  1. <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">
  2.                 <Columns>
  3.                     <asp:TemplateField HeaderText="LevelDesc" ShowHeader="False">
  4.                         <ItemTemplate>
  5.                             <asp:Label ID="lblLevelDesc" Width="150px" runat="server" Text='<%# Bind("LevelDesc") %>'></asp:Label>
  6.                         </ItemTemplate>
  7.                     </asp:TemplateField>
  8.                     <asp:TemplateField ShowHeader="False" HeaderText="LevelControls">
  9.                         <ItemTemplate>
  10.                             <asp:DropDownList ID="ddlLevel" Width="200px" Enabled="false" OnSelectedIndexChanged="ddlLevel_SelectedIndexChanged" runat="server" AutoPostBack="true" AppendDataBoundItems="true">
  11.                             <asp:ListItem Selected="True" Value="0">--Select--</asp:ListItem>
  12.                             </asp:DropDownList>
  13.                             <asp:TextBox ID="txtLeafNode" runat="server"></asp:TextBox>
  14.  
  15.  
  16.  
  17.                            <div id='divList1' runat="server"  style="Z-INDEX: 102;OVERFLOW:auto; WIDTH: 247px;height:90px" >
  18.  
  19.                             <asp:ListBox ID="LsthierA" SelectionMode="Multiple" Width="700px" runat="server" Rows="5" Height="10000">
  20.                             </asp:ListBox>
  21.  
  22.                             </div>
  23.  
  24.  
  25.                              <asp:ListBox ID="lstLevel" Width="200px" Visible="false" runat="server"></asp:ListBox>
  26.                             <asp:HiddenField ID="hdlLevelKey" Value='<%#DataBinder.Eval(Container.DataItem,"LevelKey") %>' runat="server" />
  27.                             <asp:HiddenField ID="hdIsLeafNode" Value='<%#DataBinder.Eval(Container.DataItem,"IsLeafNode") %>' runat="server" />
  28.                             <asp:HiddenField ID="hdIsRoot" Value='<%#DataBinder.Eval(Container.DataItem,"IsRoot") %>' runat="server" />
  29.                             <asp:HiddenField ID="hdDDLSelection" runat="server"/>
  30.                             <asp:HiddenField ID="hdHierKey" runat="server"/>
  31.  
  32.                             <asp:TextBox ID="txtEnterNewLevel" Width="195px" Visible="false" runat="server" Enabled="false"></asp:TextBox>
  33.                         </ItemTemplate>                      
  34.                     </asp:TemplateField>
  35.                     <asp:TemplateField HeaderText="NewLevelButton">
  36.                         <ItemTemplate>
  37.                             <asp:Button ID="btnNewLevel" OnClick="btnNewLevel_Click" runat="server" Text='<%#DataBinder.Eval(Container.DataItem,"LevelDesc") %>' />
  38.                         </ItemTemplate>
  39.                     </asp:TemplateField>
  40.                     <asp:TemplateField HeaderText="AttributeValueButton">
  41.                     <ItemTemplate>
  42.                         <asp:Button ID="btnAtVal" runat="server" Text="Add Attribute Value" OnClick="btnAtVal_Click" Width="118px" />
  43.                     </ItemTemplate>
  44.                     </asp:TemplateField>
  45.  
  46.                 </Columns>
  47.                 <FooterStyle BackColor="#CCCC99" ForeColor="Black" />
  48.                 <SelectedRowStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
  49.                 <PagerStyle BackColor="White" ForeColor="Black" HorizontalAlign="Right" />
  50.                 <HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
  51.             </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?
Jan 10 '09 #7
acoder
16,027 Recognized Expert Moderator MVP
@laks2886
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!
Jan 10 '09 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

2
2915
by: collie | last post by:
Hi, I have 2 listboxes. The first gets populated from the db as soon as the page loads. The second listbox get populated based on the user's selection from the first listbox. However, currently the code is such that with each selection there is a postback. We want to avoid it using filter and javascript. I am not using ADO.NET but adodbc and no datagrids or datasets (please don't tell me that i should as my boss clearly doesn't want...
1
9869
by: Daniel | last post by:
hi, I had an asp:listbox, and everytime i click item inside, the bar automatically go to the top, is there any way to keep the scroll position? I turn on the smartNavigation, it still doesn't work. Thanks ahead.
4
5104
by: Bob P. | last post by:
Hello, I have a page with: * two side-by-side asp:listboxes and two arrow asp:buttons allowing users to add/remove email addresses between them -- very much like Outlook, where you have the address book on the left, and you build the message recipients on the right. * an asp:button that, when clicked, fires off some code to create and send the mail message
0
1586
by: deepak | last post by:
Hi all, i m transefering values from one listbox to another listbox using javascript(both are html controls), the first listbox is populating with database at page_load time and the second listbox is empty initially .the two buttons which i have taken are both(btnAd,btnRemove) have values Add,Remove and both are input type with run as server control property set to true,.my script is given below , however when i click on add button the ...
6
5227
by: Janaka | last post by:
Help! I have two ListBox controls on my web form. The first one gets populated on entry with values from the DB. I then use JavaScript to copy options from this ListBox to my second one. (I have also tried changing the second ListBox to an HtmlSelect control) using bog standard JavaScript code like so where "used" is the name of my <select> control: used.options = new Option(name, typeId); This all works fine and I can move across...
4
2802
by: Jeff | last post by:
....still new at this. ...hopefully a simple question Is there some practical way of altering the function of a keypress in Visual Web.net 2005 using VB without causing a postback on each keypress? For example: A have a listbox with a number of selections. The up and down keyboard keys change the indicated listbox selection and by default the <tabkey takes the focus away from the listbox and onto a button that will submit the selection. I'm...
4
9384
by: Dave | last post by:
I recently found out that the RequiredFieldValidator works differently for a ListBox than I needed; it checks to see if a row is selected, rather than checking to see if the listbox is empty. I tried using a CustomValidator but it does not seem to be firing (I have e.false in the validation function but still no intervention). Does the CustomValidator also require that a row is selected? Can I use validators for this requirement or do I...
7
5619
by: Lit | last post by:
Hi, How can I capture the vertical scroll bar position for a Listbox. I have a Listbox of 100 items + when I click on it I post back remove the item selected. After returning to the client browser the list box scroll position is at the top.
15
2372
by: Doogie | last post by:
I have a .net app that a user currently enters a number in a text box, hits a button and a data call is executed. She wants the ability to enter in multiple numbers (up to 100). So to make things look better visually for that, I created a listbox under the text box. She enters the number in the text box, clicks another button I added and the number is stored in the list box. Then my plan was to grab all those numbers from the list box...
0
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9480
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10147
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10090
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
7499
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6739
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5380
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4050
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3645
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.