Link to home
Start Free TrialLog in
Avatar of Erwin Pombett
Erwin PombettFlag for Switzerland

asked on

i have chechboxes by pair, when one is checked i want the second uncheck, names are dynamic, how to?

hello,
i have a datagrid in which i set two checkboxes per line,
when one get checked i want the other, from the same line, to get uncheck,
i think javascript is the solution, but how should i fill my toogle(this) function?


function toogle(obj){
   var chkbox = obj.id
   ... how to uncheck his bro ? ;o)
}


thank you

<asp:DataGrid
        	        id="DrainGrid" 
        	        border="1" 
        	        runat="server" 
        	        pagesize="5" 
        	        allowsorting="True" 
        	        autogeneratecolumns="False"
        	        onItemDataBound="AvoidValidated"
            		showheader="False" 
            		borderstyle="solid">
            	<AlternatingItemStyle CssClass="alternate"></AlternatingItemStyle>
        		 <Columns>
 <asp:TemplateColumn>
                            <ItemTemplate>
                               <asp:Label id="ValidateDrain" runat="server">
                                  <asp:CheckBox Runat="server" id="chkToValidate" Checked='<%# DataBinder.Eval(Container.DataItem, "validated")%>' onclick="javascript:toogle(this);"></asp:CheckBox>
                                  <asp:Label Runat="server" id="labChkValidate" Text='<%# DataBinder.Eval(Container.DataItem, "DrainID") %>' Visible="false"></asp:Label>
                               </asp:Label>
                            </ItemTemplate>
                            <ItemStyle cssClass="td_75"/>
                      </asp:TemplateColumn>
                      <asp:TemplateColumn>
                            <ItemTemplate>
                               <asp:Label id="DeleteDrain" runat="server">
                                  <asp:CheckBox runat="server" id="chkToDelete" onclick="javascript:toogle(this);"></asp:CheckBox>
                                  <asp:Label runat="server" id="labChkDelete" Text='<%# DataBinder.Eval(Container.DataItem, "DrainID") %>' Visible="false" />
                               </asp:Label>
                            </ItemTemplate>
                            <ItemStyle cssClass="td_75"/>
                      </asp:TemplateColumn>
                      
                   </Columns>	
        	  </asp:DataGrid>

Open in new window

Avatar of tillgeffken
tillgeffken

ASKER CERTIFIED SOLUTION
Avatar of Thomas4019
Thomas4019
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
totally agree with Thomas
the design seems to be wrong because such a requirement can be better fulfilled by radio buttons
sorry adding on the what you are trying to do - the following link the author is using the attributes.add to attach the javascript function on click
http://forums.asp.net/t/1393456.aspx
may be that will help
Avatar of Erwin Pombett

ASKER

hello, experts,
i dont have time to correct and change to radio buttons,
i made a mistake, i 'll try to change that later.

I noticed that when displaying id of checkboxes, names for two checkbox on the same line
will have allmost the same name.
i 've try to work with that name in order to uncheck the correspondant(the one on the same line, row)

here's my function, but it 's not changigin my checkboxe as it should,  what ''s wrong?
is there anything to do with the binding?

in a row, two checkboxes on a line would have for instance :
  //DrainGrid_ctl03_chkToValidate
//DrainGrid_ctl03_chkToDelete

function toogle(obj){
    var prefixDrain = "DrainGrid_";  
    var suffixV = "_chkToValidate";
    var suffixD = "_chkToDelete";    
   
    var name = obj.id;
   
    if(name.search("_chkToValidate") > 1 ){
        var ctlId = name.split("_")[1]; // ctrlId.
        var complete = prefixDrain + ctlId + suffixD;
        //alert(complete)
        var corrDel = document.getElementById(complete);
        if(corrDel.checked)
            corrDel.cheked = false;
    }
    if(name.search("_chkToDelete") > 1 ){
        var ctlId = name.split("_")[1]; // ctrlId.
        var complete = prefixDrain + ctlId + suffixV;
        //alert(complete)
        var corrVal = document.getElementById(complete);
        if(corrVal.checked)
            corrVal.cheked = false;
    }
   
}
i also try by the method : UncheckAll(DataGrid controlGrid)  cf.code attached
is it my use of the method that has a problem?

i attached my code behind page,




public void UnCheckAll(DataGrid controlGrid)
        {
 
            foreach (DataGridItem item in controlGrid.Items)
            {
                try
                {
                    foreach (Control c in item.Cells[7].Controls)
                    {
                        if(typeof(CheckBox) == c.GetType())
                            ((CheckBox) c).Checked = false;
                    }
 
                    foreach (Control c in item.Cells[8].Controls)
                    {
                        if(typeof(CheckBox) == c.GetType())
                            ((CheckBox) c).Checked = false;
                    }
 
                }catch
                {
                    
                }
            }
        }
 
//------------------------- aspx.cs
    public partial class u1_drainsEdit : PrincipalPage
    {
 
        private IDrainController DrainController_ = null;
        //private ContainerController ContainerController_ = null;
 
 
        private Container aContainer_ = null;
        private int container_id_ = -1;
        private int ecolog_id_    = -1;
 
        ArrayList DrainsList_ = new ArrayList();
        private DateTimeFormatInfo format_;
 
 
 
        protected override void OnInit(EventArgs e)
        {
            // TODO test user register
            // valuers recues par la page view drains, qui est la seule qui envoie ici.
            container_id_ = int.Parse(Request.QueryString.Get("container_id"));
            ecolog_id_ = int.Parse(Request.QueryString.Get("ecolog_id"));
 
            DrainController_ = new DrainController(VarSession.Role, VarSession.Community, VarSession.Language);
            //ContainerController_ = new ContainerController(VarSession.Role, VarSession.Community,VarSession.Language);
 
            aContainer_ = DrainController_.Get_ContainerWithDrains(container_id_);
            format_ = new CultureInfo(VarSession.Language, false).DateTimeFormat;
 
            DrainGrid.DataBind(); // fait que le retour est affiché pareillemnet.
            AddGraphemes();
 
            base.OnInit(e);
        }
 
 
 
        protected void Page_Load(object sender, EventArgs e)
        {
            if(IsPostBack)
            {
                TheCalendar.Visible = false;
            }
            DrainsObjectsView();
            //ObjectsToDataGrid();
 
        }
 
 
 
        /// <summary>
        /// information sur le container pour lequel on edite les vidanges.
        /// </summary>
        private void AddGraphemes()
        {
            lab_containerId.Text = "<lng id=ContainerId/>" + ": ";
            lab_containerId.ToolTip = "<lng id=ContainerIdInfo/>" + ": ";
                containerId.Text = aContainer_.Id.ToString();
 
            lab_communityNo.Text = "<lng id=ContainerCommunityNumber/>" + ": ";
                communityNo.Text = aContainer_.CommunityNumber.ToString();
            lab_address.Text = "<lng id=Address/>" + ": ";
                address.Text = aContainer_.GetAddress();
            lab_wasteType.Text = "<lng id=ContainerWasteType/>" + ": ";
                wasteType.Text = aContainer_.Status.GetWasteTypeLabel();
 
            //  --| STATS |--
            DrainsStatTitle.Text = "<lng id=DrainStats/>";
            DrainLastDaysRate.Text = "<lng id=DrainLastDaysRate/>" + ": ";
            //DrainLastDaysRateValue.Text = "<lng id=DrainLastDaysRateValue/>" + ": ";
            FullLevelInRatio.Text = "<lng id=FullLevelInRatio/>" + ": ";
            AveragePercentLevel.Text = "<lng id=RatioPercentLevel/>" + ": ";
            WorstePercentLevel.Text = "<lng id=WorstePercentLevel/>" + ": ";
 
 
            //  --| ADD JS |--
        }
 
 
 
        private void DrainsObjectsView()
        {
            DrainsList_ = DrainController_.GetDrainsForInstallation(container_id_, container_id_);
            DrainGrid.DataSource = DrainsList_;
            // TODO : prendre valeurs d'un objet
            DrainLastDaysRateValue.Text     = "5+3[jours]";
            FullLevelRatio.Text             = "66%"; // soit 3 vidanges: 100, 70, 70 :  33% 
            AveragePercentLevelValue.Text   = "75%"; // soit 3 vidanges: 100, 70, 70 :  80%
            WorstePercentLevelValue.Text    = "35%";
 
 
            DrainGrid.DataBind();
        }
 
 
 
        /// <summary>
        /// creates a datatable with the right coumns.
        /// prepare the dates display type.
        /// </summary>
        /// <returns></returns>
        private DataTable GetDataTableOutOfObjects()
        {
            DataTable dt = new DataTable();
            DataRow _dr = null;
 
            dt.Columns.Add("id");
            dt.Columns.Add("container_id_");
            dt.Columns.Add("ecolog_id");
            dt.Columns.Add("drainDate");
            dt.Columns.Add("analysisDate");
            dt.Columns.Add("measureAtDrain");
            dt.Columns.Add("levelPercentAtDrain");
            dt.Columns.Add("unitsDrained");
            dt.Columns.Add("bagsDrained");
            dt.Columns.Add("validated");
 
 
            foreach (Drain aDrain in DrainsList_)
            {
                // on a besoin d'une nouvelle ligne, on la fait à la talbe
                _dr = dt.NewRow();
                // on a besoin des valauers depuis l'objet.
                _dr["id"] = aDrain.DrainID;
                _dr["container_id_"] = aDrain.ContainerId;
                _dr["ecolog_id"] = aDrain.EcologId;
                _dr["drainDate"] = ((DateTime)aDrain.DrainDate).ToString("ddd dd MMM yy, HH:mm", format_);
                _dr["analysisDate"] = aDrain.AnalysisDate;
                _dr["measureAtDrain"] = aDrain.Measure;
                _dr["levelPercentAtDrain"] = aDrain.LevelPercent;
                _dr["unitsDrained"] = aDrain.UnitsDrained;
                _dr["bagsDrained"] = aDrain.BagsDrained;
                _dr["validated"] = aDrain.Validated;
                // on ajoute la ligne à la table
                dt.Rows.Add(_dr);
            }
 
            return dt;
        }
 
 
 
 
 
#region events
        /*
        private void dataGrid1_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            info.write(this.dataGrid1[this.dataGrid1.CurrentCell.RowNumber, this.dataGrid1.CurrentCell.ColumnNumber].ToString());
        }*/
 
 
        public void AddCalView_Click(object o, EventArgs e)
        {
            TheCalendar.Visible = true;
        }
 
       
 
        protected void Calendar_SelectionChanged(object sender, EventArgs value)
        {
            labDrainInfoRep.Text = "";
            System.Web.UI.WebControls.Calendar cal = (System.Web.UI.WebControls.Calendar) sender;
            DrainDateToAdd.Text = cal.SelectedDate.ToString("dddd, dd-MM-yyyy", format_);
        }
 
        protected void Calendar_VisibleMonthChanged(object sender, System.Web.UI.WebControls.MonthChangedEventArgs e)
        {
             TheCalendar.Visible = true;
        }
 
 
        protected void SubmitDrainDate_Click(object sender, EventArgs e)
        {
            try
            {
                ///DrainViewController controller = new DrainViewController(VarSession.Role, VarSession.Community, VarSession.Language);
                string newDate = DrainDateToAdd.Text.Split(',')[1].Trim();
                DateTime _dateSelected = DateTime.ParseExact(newDate, "dd-MM-yyyy",  null); 
                bool _rep = DrainController_.UserInsertNewDrain(container_id_, container_id_, _dateSelected);
 
                if(_rep)
                {
                    infoOkAdd.Visible= true;
                    DrainDateToAdd.Text = "";
                    labDrainInfoRep.Text = "OK, press submit for refresh";
                }else
                {
                    infoOkAdd.Visible= true;
                    DrainDateToAdd.Text = "";
                    labDrainInfoRep.Text = "KO, votre vidange n'a pas été ajoutée";
                }
            }catch(Exception ex)
            {
                //infoReport.InnerHtml = "<lng id=Choisissez une date avant d'ajouter."; 
                Console.Write("01_drainsEdit->SubmitDrainDate_Click; err: " + ex.Message);
                infoReport.InnerHtml = "choisissez une date et seulement après pressez ajouter"; 
            }
        }
 
 
 
        protected void ReevaluateDrainsForContainer(object sender, EventArgs e)
        {
            ArrayList drainsCompleted = DrainController_.EvaluateDrainsToComplete(aContainer_);
            DrainController_.Update_DrainsListToComplete(drainsCompleted);
 
        }
 
 
 
        protected void SubmitDrainGrid(object sender, EventArgs e)
        {
            List<int> _responsesToValidate = new List<int>();
            List<int> _responsesToDelete = new List<int>();
            
            try
            {
                foreach(DataGridItem row in DrainGrid.Items)
                {
                    //   --| Validated Drains |--
                    if((CheckBox)row.FindControl("chkToValidate") != null) // certains check sont remplacés par le vu.
                    {
                        CheckBox checkVal = (CheckBox)row.FindControl("chkToValidate");
                        if (checkVal.Checked)
                        {
                            _responsesToValidate.Add(int.Parse(((Label)row.FindControl("labChkValidate")).Text));
                        }
                    }
 
                    //   --| Deleted Drains |--
                    if ((CheckBox)row.FindControl("chkToDelete") != null) // les checkbox qui ont mantnt une puce verte.
                    {
                        CheckBox checkDel = (CheckBox)row.FindControl("chkToDelete");
                        if (checkDel.Checked)
                        {
                            //reponsesToDelete.Add(((Label) row.FindControl("labChkDelete")).Text);
                            _responsesToDelete.Add(int.Parse(((Label)row.FindControl("labChkDelete")).Text));
                        }
                    }
                }
 
                bool val = DrainController_.ValidateDrainsList(container_id_, _responsesToValidate);
                bool del = DrainController_.DeleteDrainsList(aContainer_, _responsesToDelete);
                Repondre(val, del); 
 
                UnCheckAll(DrainGrid);
 
            }catch(Exception ex)
            {
                Response.Write("01_drainsEdit.aspx->ValidateDrains; ex: " + ex.Message);
            }
        }
 
 
        private void Repondre(bool repValid, bool repDele)
        {
            string _rep = "";
 
            if(repDele)
            {
                _rep += "1. Les vidanges ont été effacées.";
            }else
            {
                _rep += "1. Problème : vidanges pas effacées.";
            }
            
            if(repValid)
            {
                _rep += "2. Vidanges validées.";
            }else
            {
                _rep += "2. Problème : Vidanges pas validées.";
            }
 
            infoReport2.Text=  _rep;
        }
 
 
 
 
        protected void AvoidValidated(object sender, DataGridItemEventArgs e)
        {
 
            if(e.Item.Cells[0].FindControl("drainID") != null)
            {
                //Response.Write("<br> drainId:" + ((Label) e.Item.Cells[0].FindControl("drainID")).Text) ; 
            }
 
            if(e.Item.Cells[1].FindControl("ContainerId") != null)
            {
                //Response.Write("<br> contaienrId:" + ((Label) e.Item.Cells[1].FindControl("ContainerId")).Text) ; 
            }
 
            if(e.Item.Cells[2].FindControl("EcologId") != null)
            {
                //Response.Write("<br> EcologId:" + ((Label) e.Item.Cells[2].FindControl("EcologId")).Text) ; 
            }
 
            if(e.Item.Cells[3].FindControl("DrainDate") != null)
            {
                //Response.Write("<br> DrainDate :" + ((Label) e.Item.Cells[3].FindControl("DrainDate")).Text) ; 
            }
 
            if(e.Item.Cells[4].FindControl("BagsDraind") != null)
            {
                //Response.Write("<br> BagsDrained:" + ((Label) e.Item.Cells[4].FindControl("BagsDrained")).Text) ; 
            }
 
            if(e.Item.Cells[5].FindControl("UnitsDraind") != null)
            {
                //Response.Write("<br> UnitsDrained:" + ((Label) e.Item.Cells[5].FindControl("UnitsDrained")).Text) ; 
            }
 
            if(e.Item.Cells[6].FindControl("LevelPercent") != null)
            {
                //Response.Write("<br> LevelPercent:" + ((Label) e.Item.Cells[6].FindControl("LevelPercent")).Text) ; 
            }
 
            
 
            if(e.Item.Cells[7].FindControl("ValidateDrain") != null) // conteneur des check et label.
            {
                if(((CheckBox) e.Item.Cells[7].FindControl("chkToValidate")).Checked)
                {
                    HtmlImage img = new HtmlImage();
                    img.ID = "imgDrainValidated";
                    img.Src = "../Themes/base/img/vert.png";
                    e.Item.Cells[7].Controls.Clear(); // on eleve les checkbox 
                    e.Item.Cells[7].Controls.AddAt(0, img); // on le remplace par l'image validée.
                }
                //Response.Write("<br> chkToValidate:" + ((CheckBox) e.Item.Cells[7].FindControl("chkToValidate")).Checked) ; 
                //Response.Write("<br> labChkValidate:" + ((Label) e.Item.Cells[7].FindControl("labChkValidate")).Text) ; 
 
            }
 
            if(e.Item.Cells[8].FindControl("DeleteDrain") != null) // conteneur des check et label.
            {
                if(e.Item.Cells[7].FindControl("imgDrainValidated") != null){ // si la vidange à été validée elle ne peut etre effacée.
                    e.Item.Cells[8].Controls.Clear();
                }else
                {
                    
                }
                //Response.Write("<br> chkToDelete:" + ((CheckBox) e.Item.Cells[8].FindControl("chkToDelete")).Checked) ; 
                //Response.Write("<br> labChkDelete:" + ((Label) e.Item.Cells[8].FindControl("labChkDelete")).Text) ; 
            }
        }
#endregion
 
 
 
 
#region tools
        private void DisplayAL(ArrayList aList, string header)
        {
            Response.Write("<br /> header " + header + ": "); 
            foreach (string anId in aList)
            {
                Response.Write("<br /> id : " + anId);
            }
        }
 
 
        //private int howmany;
 
        public void CheckBoxes(ControlCollection cc)
        {
            int howmany = 0;
            foreach (Control c in cc)
            {
                try
                {
                    CheckBoxes(c.Controls);
                }catch { }
 
                if(c.GetType() == typeof(CheckBox))
                {
                    if(((CheckBox)c).Checked) howmany++;
                }
            }
        }
 
 
        public void UnCheckAll(DataGrid controlGrid)
        {
 
            foreach (DataGridItem item in controlGrid.Items)
            {
                try
                {
                    foreach (Control c in item.Cells[7].Controls)
                    {
                        if(typeof(CheckBox) == c.GetType())
                            ((CheckBox) c).Checked = false;
                    }
 
                    foreach (Control c in item.Cells[8].Controls)
                    {
                        if(typeof(CheckBox) == c.GetType())
                            ((CheckBox) c).Checked = false;
                    }
 
                }catch
                {
                    
                }
            }
        }
#endregion tools
 
 
 
 
    }

Open in new window