简体   繁体   中英

disable and enable textbox on checkbox click in table

i have table populated with data then i add checkbox and textbox into it. below is my code:

int count1 = 0;
        TableCell tc;
        foreach (TableRow tr in Resource_TBL.Rows)
        {
            tr.Cells.Add(tc = new TableCell());
            CheckBox cbox = new CheckBox();
            cbox.ID = ""+count1;
            cbox.Attributes.Add("onclick", "document.getElementById('textbox_" + count1 + "').disabled=this.checked;");
            tc.Controls.Add(cbox);

            tr.Cells.Add(tc = new TableCell());
            TextBox tbox = new TextBox();
            tbox.ID = "textbox_" + count1;
            tbox.CssClass = "form-control";
            tbox.Enabled = false;
            tbox.Attributes.Add("placeholder", "Enter Detail Here");
            count1 += 1;
            tc.Controls.Add(tbox);
        }

i have tried :

cbox.Attributes.Add("onclick", "document.getElementById('textbox_" + count1 + "').Enabled=this.checked;");

but its not working. have an error saying(Unable to set property 'Enabled' of undefined or null reference)

is there any other way of doing it?

I don't think there's an "Enabled" property for the textbox simply because its name is in Pascal-case. :)

cbox.Attributes.Add("onclick", "document.getElementById('textbox_" + count1 + "').disabled = !this.checked;");

我认为您的ID是错误的,我建议您使用jquery,它在语法上更短,更易于阅读。

int count1 = 0;
        TableCell tc;
        foreach (TableRow tr in Resource_TBL.Rows)
        {
            CheckBox cbox = new CheckBox();
            cbox.ID = ""+count1;
            TextBox tbox = new TextBox();
            tbox.ID = "textbox_" + count1;
            tbox.CssClass = "form-control";
            tbox.Enabled = false;
            tbox.Attributes.Add("placeholder", "Enter Detail Here");
            count1 += 1;
            cbox.Attributes.Add("onclick", "document.getElementById('" + tbox.ClientID + "').disabled=!this.checked;");
            tr.Cells.Add(tc = new TableCell());
            tc.Controls.Add(cbox);
            tr.Cells.Add(tc = new TableCell());
            tc.Controls.Add(tbox);
        }

Its all about the order. don't manually use the ID because when you use masterpage or other controls then the ID will change on the page itself. Use ClientID to know what the ID of the control is on the page.

Create controls first. then add them to your table hierachy later. Also you might want to put a ! before this.checked. else your textbox will be disabled as soon your checkbox gets selected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM