• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1411
  • Last Modified:

Toggle checkboxes in dropdown with javascript

Hello Experts,
I have a dropdown with labels and checkboxes. One of the selections is "all". When the user toggles this checkbox on I want all checkboxes to be toggled on. When the use toggles this checkbox off, I want all checkboxes to be toggled off.

I would like to do this client side and tried to use the function "StopProgagation" (see below). I was however not able to get the correct code to find out if the "all" is selected and then to change the toggles of all items.

Hope you can help me with this.

Thanks a lot in advance,

MB


Server side
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If Not Page.IsPostBack Then
            Dim SelectedVessel As String = ""
            Dim cboItemVessel As String = ""
            Dim daVessels As SqlDataAdapter
            Dim dtVessels As DataTable = Nothing
            Dim VesselClass As String = "None"

            Try
                Connection.Open()
                daVessels = New SqlDataAdapter("SELECT [VesselName], [Class] FROM[VESSELREPORTING].[dbo].[Vessels] WHERE [Status]='10' AND [Operator]='Green Reefers' ORDER BY CASE WHEN [Class]='No' then 'zzzz' else [Class] END ASC, [VesselName] ASC", Connection)
                dtVessels = New DataTable
                daVessels.Fill(dtVessels)
            Finally
                Connection.Close()
            End Try

            For Each VesselRow As DataRow In dtVessels.Rows
                If VesselRow.Item("Class") <> VesselClass Then 'New VesselClass (add separator)
                    VesselClass = VesselRow.Item("Class")
                    Dim ClassItem As New RadComboBoxItem()
                    ClassItem.Text = VesselRow.Item("Class") & " class"
                    ClassItem.IsSeparator = True
                    cboVessels.Items.Add(ClassItem)
                    Dim VesselItem As New RadComboBoxItem()
                    VesselItem.Text = VesselRow.Item("VesselName")
                    cboVessels.Items.Add(VesselItem)
                Else 'New vessel
                    Dim VesselItem As New RadComboBoxItem()
                    VesselItem.Text = VesselRow.Item("VesselName")
                    cboVessels.Items.Add(VesselItem)
                End If
            Next

            Dim ItemAll As New RadComboBoxItem()
            ItemAll.Text = "All vessels"
            cboVessels.Items.Insert(0, ItemAll)

            Me.cboVessels.DataBind()

            Dim Items As String() = Split(Request.QueryString("FindPosition"), ",")
            SelectedVessel = Items(0)

            If Not SelectedVessel = "" Then
                For Each Vessel As RadComboBoxItem In cboVessels.Items
                    If Vessel.Text = SelectedVessel Then
                        'Debug.WriteLine(Vessel.Text)
                        CType(Vessel.FindControl("CheckBox"), CheckBox).Checked = True
                        Vessel.Selected = True
                    End If
                Next
            End If
            'ShowVessels()
        End If

        Debug.WriteLine("1. trigger vessel positions")

        Dim ControlID As String = ""
        ControlID = Request.Params.[Get]("__EVENTTARGET")
        If ControlID = "cboVessels" Then
            'Debug.WriteLine("2. trigger vessel positions")
            'ShowVessels()
        End If

    End Sub

Client side
<script type="text/javascript">
            //Turn debugging messages on? [use "true" instead of ""]
            var debug = "true";
            var cancelDropDownClosing = false;
            
            function StopPropagation(e)
            {
                //Cancel bubbling
                e.cancelBubble = true;
                if (e.stopPropagation)
                {
                    e.stopPropagation();
                }
                (debug) ? alert('DEBUG (CheckToggles)') : "" ;
            }

            function onDropDownClosing()
            {
                cancelDropDownClosing = false;
            }

            function ShowVessels()
            {
                cancelDropDownClosing = false;
                __doPostBack('ShowVessels','');
            }
        </script>





<telerik:RadComboBox
                    ID="cboVessels"
                    Runat="server"
                    AutoPostBack="True"
                    Width="200"
                    OnClientDropDownClosed="ShowVessels"
                    HighlightTemplatedItems="True">
                    <ItemTemplate>
                        <div onclick="StopPropagation(event)">
                            <asp:CheckBox runat="server" ID="CheckBox"
                                Visible='<%# iif(Convert.ToBoolean(DataBinder.Eval(Container, "IsSeparator")), false, true) %>' />  
                            <asp:Label ID="Label" runat="server"
                                AssociatedControlID="CheckBox"
                                Text ='<%# DataBinder.Eval(Container, "Text") %>'>
                            </asp:Label>
                        </div>
                    </ItemTemplate>
                </telerik:RadComboBox>

Open in new window

Screenshot1.jpg
0
mark_norge
Asked:
mark_norge
1 Solution
 
InsoftserviceCommented:
hi ,

The above code is applicable in such a format

         
                                  ALLCHKBOX
id   name    address chkbox
1    xyz       india        chkbox
2   abc        india        chxbox

where chkbox => check box which can be selected manually one by one.

ALLCHKBOX  =>  It will automatically select all check boxes of the page

code for it is

ALLCHKBOX <input type="checkbox" value="allselected" name="allselected"  id="allselected" onclick="javascript:selectAll('yourformname','chkbox[]','allselected');" />

<script type ="javascript">
//use to select all check boxxes
function selectAll(formname,checkboxname,clickboxname)
{

      var form = $(formname);
      var checkbox = form.getInputs('checkbox', checkboxname)
      checkbox.each(function(item,index)
            {
                  var objid = item.value;
                  if($(clickboxname).checked ==true)
                  {
                  item.checked =true;
                  }
                  else
                  {
                  item.checked =false;
                  }
            });
           

}
</script>


checkboxname  => individual chk boxes name
 
clickboxname  => chk box name of ALLCHKBOX

formname = > form name of your page.

Even Add above code .

RESULT:-

Similar to yahoo  individual check boxes
ALLCHKBOX will work as select all
Add a button for delete with the post chkbox[] as above note

It will help you

use prototype.js as framework
0
 
urspskCommented:
Hai,

I am not aware of the ASP.Net code, but i have a wrote a client side(javascript) function for you question. Please call this function in your checbox in which you are going to use as an TOGGLE checkbox.

function togCBox(){
frmObj = document.chkBox;
for(l='0';l
In the above function the name "master" refer to the TOGGLE checkbox and the name "chkBox" refer to the Form name where the checbox are located.
Please let me know if you have any queries.
 
0
 
siddagrlCommented:
Two points:

1. We need to check / uncheck the "select all" checkbox also. if user selects / deselects all checkboxes manually.
2. This could be written in simpler way.

Attached is the code.
<html> <title>Checkbox select all</title> <head> <body>

<script>
function selectAll(obj)
{
   var items = document.siddagrl.elements['myCheckbox'];
   for (i = 0; i < items.length; i++)
      items[i].checked = obj.checked;
}

function clicked(obj)
{
   var cnt = 0;
   var items = document.siddagrl.elements['myCheckbox'];
   for (i = 0; i < items.length; i++)
      if (items[i] != obj && items[i].checked)
         cnt++;

   if (cnt == items.length - 1)
      document.siddagrl.sAll.checked = obj.checked;
}

</script>

<form name="siddagrl">
   select all <input type="checkbox" name="sAll" onClick="selectAll(this)"><br>

   <input type="checkbox" name="myCheckbox" onClick="clicked(this)" checked><br>
   <input type="checkbox" name="myCheckbox" onClick="clicked(this)"><br>
   <input type="checkbox" name="myCheckbox" onClick="clicked(this)"><br>
   <input type="checkbox" name="myCheckbox" onClick="clicked(this)"><br>
</form>

</body> </head> </html>

Open in new window

0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
siddagrlCommented:
My first point could be rephrased as:

1.  "select all" checkbox also should get checked / unchecked automatically if user selects / deselects all checkboxes manually.
0
 
mark_norgeAuthor Commented:
Hi Experts,

Thanks for the responses. I used the code above in the following way.

My combobox uses a div to have a checkbox and label for each item. Selecting the checkbox or label should result in the same action. I could get this to work using the below code (I am quite sure it can be condensed looking at the responses you send).

I can now check or uncheck all checkboxes depending on the checkbox "All vessels". However I am not able to find out is if the checkbox "All vessels" was the checkbox that actually changed. I tried to use the onselecteditemchanged event, but (1) this only seems to detect a change of the label and not a change of a checkbox and (2) the event is not fired in combination with the event e.cancelbubble used to prevent the dropdown from closing.

I therefore tried the following. Use the onclick event and place my code before the line e.cancelbubble. This should work if I was able to find out what the changed item is, and I am not. I hope you can help with this.

Thanks in advance,
Mark

    <telerik:RadCodeBlock ID="RadCodeBlock" runat="server">
        <script type="text/javascript">
           
            function StopPropagation(e)
            {
           
                e.cancelBubble = true;
                if (e.stopPropagation)
                {
                    e.stopPropagation();
                }
               
                //I AM NOT ABLE TO FIND OUT WHICH ITEM CHANGED              
                //Check all or none
                var Items = combo.get_items();
                var ItemAllVessels = Items.getItem(0).get_element();
                var InputAllVessels = ItemAllVessels.getElementsByTagName("input");
                   
                for (var InputIndex = 0; InputIndex < InputAllVessels.length; InputIndex ++)
                {
                    var Input = InputAllVessels[InputIndex];
                    if (Input.type == "checkbox")
                    {
                        if(Input.checked == true)
                        {
                            //All vessels is checked
                            for(var i=0; i<Items.get_count(); i++)      
                            {
                                var ItemVessels = Items.getItem(i).get_element();
                                var InputVessels = ItemVessels.getElementsByTagName("input");
                                                           
                                for (InputIndex = 0; InputIndex < InputAllVessels.length; InputIndex ++)
                                {
                                    Input = InputVessels[InputIndex];
                                    if(Input != null)
                                    {
                                        if (Input.type == "checkbox")
                                        {
                                            Input.checked = true
                                        }
                                    }
                                }
                             }
                        }
                        else
                        {
                            //All vessels is not checked
                            for(i=0; i<Items.get_count(); i++)      
                            {                            
                                ItemVessels = Items.getItem(i).get_element();
                                InputVessels = ItemVessels.getElementsByTagName("input");
                                                           
                                for (InputIndex = 0; InputIndex < InputAllVessels.length; InputIndex ++)
                                {
                                    Input = InputVessels[InputIndex];
                                    if (Input != null)
                                    {
                                        if (Input.type == "checkbox")
                                        {
                                            Input.checked = false
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            function OnClientSelectedIndexChanged(sender, eventArgs)
            {
                //THIS ONLY LOOKS AT THE LABELS AND NOT THE CHECKBOXES
                var item = eventArgs.get_item();
            }
           
            function ShowVessels()
            {
                __doPostBack('ShowVessels','');
            }
        </script>
    </telerik:RadCodeBlock>
   
    <table style="width: 100%; height: 100%;">
        <telerik:RadAjaxManagerProxy ID="RadAjaxManagerProxy1" runat="server">
            <AjaxSettings>
                <telerik:AjaxSetting AjaxControlID="cboVessels">
                    <UpdatedControls>
                        <telerik:AjaxUpdatedControl ControlID="cboVessels" />
                        <telerik:AjaxUpdatedControl ControlID="cboVesselsComp" />
                        <telerik:AjaxUpdatedControl ControlID="GMap1" />
                    </UpdatedControls>
                </telerik:AjaxSetting>
            </AjaxSettings>
        </telerik:RadAjaxManagerProxy>
   
        <tr style="height: 20px">
            <td style="width: 200px">
                <telerik:RadComboBox
                    ID="cboVessels"
                    Runat="server"
                    AutoPostBack="True"
                    Width="200"
                    Height="400"
                    OnClientDropDownClosed="ShowVessels"
                    OnClientSelectedIndexChanged="OnClientSelectedIndexChanged"
                    HighlightTemplatedItems="True">
                    <ItemTemplate>
                        <div
                            id="divVessels"
                            onclick="StopPropagation(event)">
                            <asp:CheckBox runat="server" ID="CheckBox"
                                Visible='<%# iif(Convert.ToBoolean(DataBinder.Eval(Container, "IsSeparator")), false, true) %>' />  
                            <asp:Label ID="Label" runat="server"
                                AssociatedControlID="CheckBox"
                                Text ='<%# DataBinder.Eval(Container, "Text") %>'>
                            </asp:Label>
                        </div>
                    </ItemTemplate>
                </telerik:RadComboBox>
0
 
siddagrlCommented:
@mark_norge

I do not see the combo box in the screenshot you attached intially. Could you paste a latest screenshot and also elaborate your question?
0
 
mark_norgeAuthor Commented:
Thanks for replying siddagrl,

I attached the combobox (closed and opened). What I want to achieve is:
1. The ability for the user to select select one or more vessels (by selecting the checkbox or label of an item in the div). During the selection the dropdown should not be closed (this is why I use e.cancelbubble in the function stoppropagation).
2. The ability for the user to select or deselect "all vessels". If this checkbox is selected all checkboxes should be (un)checked. The dropdown should also not be closed.

(1) works correctly and (2) works partly. I can check and uncheck all checkboxes, but the code runs on every changed item, while it should only run when "all vessels" changed.

Hope I explained it correctly and you can help me.
Regards, MB
screenshot-1.jpg
screenshot-2.jpg
0
 
siddagrlCommented:
Thanks mark_norge for posting screenshots & explanation and now i understood your problem.

But i have never worked on ASP / .NET and your problem seems to be integrated with telerik along with ASP.

I am still trying to understand the generated HTML & javascript code for your problem that works on client side (browsers) and will update you ASAP.
0
 
mark_norgeAuthor Commented:
Thanks siddagrl,
Using the links you provided I got to the right solution.
Regards, MB
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now